【发布时间】:2021-04-21 12:46:37
【问题描述】:
我有一个 utils.js 文件,其中的一个函数调用同一文件中的另一个函数。像这样:
// utils.js
async function originalFunc (params) {
...
await anotherFunc(arg1, arg2)
}
在另一个文件中,我正在使用 jest 来测试 originalFunc
// utils.test.js
test('should test orginalFunc', async () => {
const params = {
arg1: 'data1',
arg2: 'data2',
}
const anotherFunc = jest.fn()
await util.originalFunc(params)
// todo: expect anotherFunc to be called with correct params
})
但是,当使用此配置时,调用的是真正的 anotherFunc,而不是模拟的 jest.fn() 版本。
我也尝试过像这样模拟模块:
jest.mock('../src/util', () => ({
...jest.requireActual('../src/util'),
anotherFunc: jest.fn(),
}));
但这也不起作用。
如何强制originalFunc 使用anotherFunc 的模拟实现?
【问题讨论】:
-
有一个论据表明您不能通过设计来测试它——在任何其他语言中,您通常不会对私有方法进行单元测试。验证结果不是一样好吗?
标签: javascript node.js unit-testing jestjs mocking