jeudi 15 avril 2021

Jest test fails if two methods are mocked

I have a confusing situation on my tests. See the code below.

file.js

class Test {
  constructor() {}

  async main() {
    const a = await this.aux1("name1");
    const b = await this.aux2("name2");
  }

  async aux1(name) {
      console.log(name)
  }

  async aux2(name) {
    console.log(name)
  }
}

module.exports = Test;

file.spec.js

describe('Concept proof', () => {
    const module = require("./file.js");
    const inst = new module();

    test('should call aux1', async () => {
        const a = jest.fn(() => "return");

        inst.aux1 = a
        inst.main()

        expect(a).toHaveBeenCalled()
    });

    test('should call aux2', async () => {
        const b = jest.fn(() => "return");

        inst.aux2 = b
        inst.main()

        expect(b).toHaveBeenCalled()
    });
});

result

    expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

      18 |         inst.main()
      19 |
    > 20 |         expect(b).toHaveBeenCalled()
         |                   ^
      21 |     });
      22 | });

      at Object.<anonymous> (file.spec.js:20:19)

The method aux2 is not invoked if aux1 is called from main, but behave as expected if I remove aux1 call from main.

I was not able to find an explanation for that behave on the docs. I'm misunderstanding something, or the normal behave should be aux2 be called even if aux1 is called before? Any help will be appreciated!

Any help will be apreciated!

Aucun commentaire:

Enregistrer un commentaire