我正在为一个函数编写单元测试,该函数调用同一模块中的另一个函数。
例
export function add(a, b) {
return a + b
}
export function showMessage(a, b) {
let sum = add(a, b)
return `The sum is ${sum}`
}
测试:
import * as Logics from './logics;
describe('showMessage', () => {
it('should return message with sum', () => {
let addSpy = jest.spyOn(Logics, 'add')
let showMessageResponse = Logics.showMessage(2, 2)
expect(addSpy).toHaveBeenCalledTimes(1)
});
});
我想测试一下在执行showMessage的时候,add函数是否被调用。上面的一个给出了以下错误:
预期呼叫数:1接收的呼叫数:0
我找到了一个解决方案,但需要改变函数的导出方式:
function add(a, b) {
return a + b
}
function showMessage(a, b) {
const sum = Logics.add(a, b)
return `The sum is ${sum}`
}
const Logics = {
showMessage,
add
}
export default Logics
我不想更改导出函数的方式。
2条答案
按热度按时间mspsb9vt1#
简而言之,如果不改变导出,你就无法真正实现它。你可以阅读原因(也许还有其他选项on this answer以及这个答案)。
一个更好的选择imo会像这样(在你的logics.js文件中):
然后在
showMessage
函数中使用它,就像你在第二个例子中所做的那样:基本上,只需导入logics.js中的所有内容,并使用该值来获取对相同
add
函数的引用。补充说明:虽然正确地模拟了
add
,但它与showMessage中调用的函数不同,基本上不能模拟该函数(您也可以检查此代码以获得证明)还发布了in this sandbox
5cg8jx4n2#
理想情况下,你应该独立于功能进行测试,一个测试不负责另一个功能的测试功能。
这不是最好的方法,但你可以这样做:
util.js
在你的测试中,你可以这样做:
util.test.js
下面是你可以玩的沙盒:https://codesandbox.io/s/jest-test-forked-9zk1s4?file=/util.test.js:0-366