【发布时间】:2021-09-06 16:31:34
【问题描述】:
我在prepareStatement.ts 中有一个函数processCosts。 processCosts 调用一个函数,calculatePrice 从 coreLogic.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