【问题标题】:Jest test fails if two methods are mocked如果模拟了两种方法,则 Jest 测试失败
【发布时间】:2021-04-15 20:20:11
【问题描述】:

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

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

结果

    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? 任何帮助将不胜感激!

我们将不胜感激!

【问题讨论】:

  • 你为什么要修补你应该测试的东西的一部分?另请注意,您的测试泄漏状态 - inst 仅创建一次,因此随着时间的推移,它的更多方法会被模拟替换。
  • 只是让示例更简单。我发现没有理由带来比需要更多的代码。

标签: javascript testing jestjs mocking


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    • 1970-01-01
    • 2021-03-16
    相关资源
    最近更新 更多