typescript - 用玩笑模拟在打字稿测试中从另一个文件调用的函数
问题描述
我有一个函数processCosts
。调用一个函数,从.prepareStatement.ts
processCosts
calculatePrice
coreLogic.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);
解决方案
这就是修复它的原因。我将 jest.mock(...) 移到了 describe(...) 和 it(...) 到文件的顶层,一切都开始工作了。
推荐阅读
- node.js - 从 mongodb 获取“相关文档”
- reactjs - 切换按钮加载状态错误:重新渲染过多
- c++ - 如何调整窗口边框大小
- javascript - 适合在 THREE.js 中缩放平面上的映射纹理
- azure - 如何在 Azure DevOps 中使部分成功的阶段失败?
- redux - Redux - createSlice 内的标准化嵌套数据组织
- azure - 在 Azure 数据工厂的查找阶段在 SQL 查询中传递动态内容
- excel - 如果 Contes = 0,则清除范围的单元格内容
- node.js - 将用户表 aws cognito 移动到 MongoDB
- python-3.x - 由于 ModuleNotFoundError 无法运行运行脚本:没有名为“webdriver_manager”的模块 Ubuntu Python