[英]Jest doesn`t mock(set spy) on needed function
我的測試函數reverseAdd調用了在同一模塊中定義的另一個函數add 。 我需要測試,如果測試功能調用另一個。
模組
function add(a, b) {
return a + b;
}
function reverseAdd(a, b) {
add(b, a);
}
module.exports = {
add,
reverseAdd
}
測試
const exp = require('./add');
describe('add', () => {
it('should add two numbers', () => {
expect(exp.add(1, 2)).toBe(3);
});
it('should add two numbers', () => {
exp.add = jest.fn();
exp.reverseAdd();
expect(exp.add).toHaveBeenCalledTimes(1);
});
});
結果
Expected mock function to have been called one time, but it was called zero
據我了解,包裝函數是另一個函數,在測試函數中未調用它。
我如何包裝/間諜功能添加 ?
謝謝@ltamajs,我找到了解決方案 。
需要重寫模塊到
function add(a, b) {
return a + b;
}
function reverseAdd(a, b) {
module.exports.add(b, a); <----- here changes
}
module.exports = {
add,
reverseAdd
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.