首页 > 解决方案 > 用玩笑模拟在打字稿测试中从另一个文件调用的函数

问题描述

我有一个函数processCosts。调用一个函数,从.prepareStatement.tsprocessCostscalculatePricecoreLogic.ts

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

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

标签: typescriptjestjsmockingts-jest

解决方案


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


推荐阅读