首页 > 解决方案 > 如果模拟了两种方法,则 Jest 测试失败

问题描述

我在测试中遇到了令人困惑的情况。请参阅下面的代码。

文件.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;

文件.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()
    });
});

结果

    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)

如果从 main 调用 aux1,则不会调用方法 aux2,但如果我从 main 中删除 aux1 调用,则会按预期运行。

我无法在文档中找到该行为的解释。我误解了一些东西,或者即使之前调用了 aux1,也应该调用正常的行为 aux2?任何帮助将不胜感激!

任何帮助将不胜感激!

标签: javascripttestingjestjsmocking

解决方案


你应该使用await inst.main();.

inst.main()是一种异步方法。如果await不使用,主线程会继续执行,不会等待inst.main().

这意味着该expect(b).toHaveBeenCalled()语句将在inst.main()方法之前执行。


推荐阅读