我有一个名为helper.js的文件,其中包含两个函数
export const funcA = (key) => {
return funcB(key)
};
export const funcB = (key,prop) => {
return someObj;
};
Run Code Online (Sandbox Code Playgroud)
我有我的helper.spec.js来测试helper.js文件的功能。
import {funcA,funcB} from 'helper';
describe('helper', () => {
test('testFuncB', () => {
}
test('testFuncA', () => {
}
}
Run Code Online (Sandbox Code Playgroud)
对funcB的测试非常简单,我只调用它并期望someObj
。问题是测试funcA,为了对其进行测试,我想模拟funcB的响应。
我希望testFuncB调用实际的funcB,而testFuncA调用模拟的funcB
我如何在两个测试中实现对funcB的模拟和原创?
这不是重复项。这是不同的情况:它们仅模拟内部调用的函数,如果我删除了testFuncB,那将是相同的,但是我也必须对testFuncB进行测试。
我正在为一个函数编写单元测试,该函数调用同一模块内的另一个函数。
例如。
export function add(a, b) {
return a + b
}
export function showMessage(a, b) {
let sum = add(a, b)
return `The sum is ${sum}`
}
Run Code Online (Sandbox Code Playgroud)
测试:
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)
});
});
Run Code Online (Sandbox Code Playgroud)
我想测试执行 showMessage 时是否调用了 add 函数。上面的一个给出了以下错误:
预计来电次数:1 已接来电次数:0
我找到了一个解决方案,但这需要更改函数的导出方式:
function add(a, b) {
return a + b
}
function showMessage(a, b) …Run Code Online (Sandbox Code Playgroud)