[英]Testing nested function in Jest
I have in file.js code which I simplify this way:我有file.js代码,我以这种方式简化:
function Apple(,data) {
this.attr1 = data.attr1,
this.attr2 = data.attr2,
this.doSomething(data.flag);
}
Apple.prototype = new function() {
this.function1 = function() {
// do something
}
this.doSomething = function(flag) {
// return value
}
}
I want to test function1()
, for that, I want to mock first doSomething()
to return a specific value, but I am failing because any call to Apple()
function executes immediately doSomething()
:我想测试function1()
,为此,我想先模拟doSomething()
以返回特定值,但我失败了,因为对Apple()
function 的任何调用都会立即执行doSomething()
:
describe('Apple', () => {
test('test function1()', () => {
Apple.doSomething = jest.fn().mockImplementation((2) => {
// do something;
});
let apple = new Apple(data); // the original doSomething() executes here instead of the mocked version
});
});
How can I achieve my goal?我怎样才能实现我的目标?
Try using spyOn
:尝试使用spyOn
:
const mockDoSomething = jest.spyOn(Apple.prototype, 'doSomething').mockReturnValueOnce((flag) => {
// mock do something;
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.