【发布时间】:2018-03-22 21:19:09
【问题描述】:
我对 node 和 javascript 非常陌生,并尝试使用 jest 编写一个 unittet,我只需要模拟一个类(和对象)的 1 个函数。
这是我正在使用的模板:
// myModule.js
class MyModule {
constructor() {
console.log("hello");
}
getCases(){
return 2;
}
getOtherCases(){
return 3;
}
}
module.exports = MyModule;
和测试:
// myModule.test.js
jest.unmock('./myModule.js');
const myModule = require('./myModule.js');
myModule.getCases = jest.fn();
describe('Test mock function', () => {
beforeAll(() => {
myModule.getCases.mockImplementation(() => 32);
mod = new myModule();
});
it('should pass', () => {
console.log(mod.getCases());
console.log(myModule.getCases());
});
});
这里的问题是mod.getCases() 没有模拟函数(myModule.getCases() 可以)
console.log myModule.test.js:12
2
console.log myModule.test.js:13
32
我需要一种特定的方式来创建对象以便模拟函数吗?
【问题讨论】:
-
尝试用
myModule.prototype.getCases代替myModule.getCases。如果这是我将在答案中解释的解决方案。 -
是的,行得通!如果您也提供答案,那就太好了:)
标签: javascript node.js unit-testing mocking jestjs