【问题标题】:Mocking a function which is called from another file in typescript tests with jest用玩笑模拟打字稿测试中从另一个文件调用的函数
【发布时间】:2021-09-06 16:31:34
【问题描述】:

我在prepareStatement.ts 中有一个函数processCostsprocessCosts 调用一个函数,calculatePricecoreLogic.ts 导入。

我有一个测试文件reports.integration.ts 导入processCosts,但我想模拟calculatePrice,这是processCosts 调用的函数。我在__mocks__ 文件夹下创建了一个文件coreLogic.ts,内容如下:

export const calculatePrice = jest.fn(() => {});

然后在我的测试文件中,在我的测试it(...) 之外,但在我写的describe(...) 之内

jest.mock('../statements/prepareStatement');

最后,测试本身:

it('should calculate processCost and 4 x what calculatePrice returns', async () => {
    (calculatePrice as jest.Mock).mockImplementationOnce(() => 100.00);
    expect(processCost).to.equal(400.00); // processCost will do 4*whatever calculatePrice is
}

当我运行我的代码时,我得到了

TypeError: coreLogic_1.calculatePrice.mockImplementationOnce is not a function

谁能指出我哪里出错了?与我所做的事情类似的人正在调用他们在测试中模拟的方法,而不是在另一个导入的函数中。无论如何,在附加调试器后,我的代码在这一行上犹豫不决:

(calculatePrice as jest.Mock).mockImplementationOnce(() => 100.00);

【问题讨论】:

  • prepareStatement 与 coreLogic 有什么关系?请给minimal reproducible example。另请注意,如果您的 jest.mock 不在文件的顶层,它不会被提升,因此测试和实际代码中的导入可能会获得原始版本。
  • 这就是修复它的原因。我将jest.mock(...)describe(...)it(...) 之外的jest.mock(...) 移到文件的顶层,一切都开始工作了。

标签: typescript jestjs mocking ts-jest


【解决方案1】:

这就是修复它的原因。我将 jest.mock(...) 移到 describe(...) 和 it(...) 之外的文件的顶层,一切都开始工作了。

【讨论】:

    猜你喜欢
    • 2018-09-16
    • 2019-09-26
    • 2019-02-06
    • 2017-01-30
    • 2020-07-09
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2020-01-31
    相关资源
    最近更新 更多