lundi 26 novembre 2018

Mocking a returned object with Jest

Consider the following case:

// File: A.js
export class A {
    constructor(b) {
        this.b = b;
    }

    sayHello() {
        this.b.getC().sayHello();

        // ...
    }
}

// File: A.test.js
jest.mock('./B')

test('should say hello', () => {
    const a = new A(new B());

    a.sayHello(); // <-- error: "Cannot read property 'sayHello' of undefined" 

    // ...
});

As you see, the class B is mocked, so it can't access it's dependency (class C) to call a method on it, hence throwing the following error:

error: "Cannot read property 'sayHello' of undefined"

The approaches I tried to no avail include:

  1. Adding a jest.mock('./C') line to A.test.js file
  2. Creating a __mocks__/A.js manual mock

So, how should cases like these (nested dependencies) be mocked out in Jest?

Aucun commentaire:

Enregistrer un commentaire