[英]Mocking a function which is called from another file in typescript tests with jest
我在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);
这就是修复它的原因。 我将 jest.mock(...) 外的 describe(...) 和 it(...) 移动到文件的顶层,一切都开始工作了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.