简体   繁体   English

在打字稿测试中用玩笑模拟从另一个文件调用的函数

[英]Mocking a function which is called from another file in typescript tests with jest

I have a function processCosts in prepareStatement.ts .我在prepareStatement.ts有一个函数processCosts processCosts calls a function, calculatePrice imported from coreLogic.ts . processCosts调用一个函数, calculatePrice进口coreLogic.ts

I have a test file reports.integration.ts which imports processCosts but I want to mock calculatePrice , which is the function processCosts calls.我有一个测试文件reports.integration.ts ,它导入processCosts但我想模拟calculatePrice ,这是函数processCosts调用。 I created a file coreLogic.ts under my __mocks__ folder with the content:我在__mocks__文件夹下创建了一个文件coreLogic.ts ,内容如下:

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

and then in my test file, outside my test's it(...) , but inside the describe(...) I wrote然后在我的测试文件中,在我的测试之外it(...) ,但在我写的describe(...)

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

Finally, the test itself:最后,测试本身:

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
}

When I run my code I get当我运行我的代码时,我得到

TypeError: coreLogic_1.calculatePrice.mockImplementationOnce is not a function

Can someone point out where I've gone wrong?有人能指出我哪里出错了吗? The people who have done something similar to what I have done are calling the method they mock in their test as opposed to inside another imported function.做过类似于我所做的事情的人正在调用他们在测试中模拟的方法,而不是在另一个导入的函数中调用。 Regardless, after attaching a debugger, my code baulks on this line:无论如何,在附加调试器后,我的代码在这一行中停滞不前:

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

this is what fixed it.这就是修复它的原因。 I moved the jest.mock(...) outside the describe(...) and it(...) to the top level of the file and everything started working.我将 jest.mock(...) 外的 describe(...) 和 it(...) 移动到文件的顶层,一切都开始工作了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM