我试图在使用 module.exports 时模拟一个特定的函数。我如何测试内部函数 B?
在我的 worker.js 中
module.exports = function () {
this.funcA = funcA
this.funcB = funcB
}
funcA () {
funcB()
}
funcB() {...}
在我的 worker-test.js 中
const Worker = require('./worker')
test('test functionB', () => {...})
test('test functionA', () => {
const work = new Worker()
work.funcB = jest.fn() //mock funcB
work.funcA //run funcA
expect(work.funcB).toHaveBeenCalledTimes(1) //Error
})
我是 Jest 新手。在这种情况下有什么好的方法来模拟函数吗?
最佳答案
由于 funcA
直接调用 funcB
,因此无法按照当前编写代码的方式模拟 funcB
。
修复它的最简单方法是注意 worker.js
返回一个构造函数,funcA
和 funcB
几乎 prototype methods ...
...如果您使它们成为原型(prototype)方法,则可以模拟 funcB
:
worker.js
class Worker {
funcA() {
this.funcB();
}
funcB() {
throw new Error('should not make it here');
}
}
module.exports = Worker;
worker.test.js
const Worker = require('./worker');
test('test functionB', () => { /* ... */ })
test('test functionA', () => {
const spy = jest.spyOn(Worker.prototype, 'funcB'); // <= spy on funcB
spy.mockImplementation(() => {}); // <= mock funcB
const work = new Worker();
work.funcA(); // <= call funcA
expect(spy).toHaveBeenCalledTimes(1); // Success!
spy.mockRestore(); // <= restore funcB
})
关于javascript - Jest : How to mock one specific function when using module. 导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55821609/