jest.spyOn 从副作用调用调用时不工作
jest.spyOn is not working when called from a side effect call
我有以下场景:
const doSomething = () => {
const test = 1;
doAnotherThing();
return test + 1;
};
const doAnotherThing = () => {};
module.exports = {
doSomething,
doAnotherThing
};
这是我的测试:
const MyModule = require('./myModule');
describe('MyModule', () => {
it('Should be able to spy another call', () => {
const spy = jest.spyOn(MyModule, 'doAnotherThing');
MyModule.doSomething();
expect(spy).toHaveBeenCalledTimes(1);
});
});
问题,有没有办法让 doSomething() 中的 doAnotherThing() 调用以某种方式被玩笑窥探,而不使用 rewire 等解决方案?
在此处找到解决方案:https://medium.com/welldone-software/jest-how-to-mock-a-function-call-inside-a-module-21c05c57a39f
为此重新定义了我的模块,现在可以使用了
const doSomething = () => {
const test = 1;
MyModule.doAnotherThing();
return test + 1;
};
const doAnotherThing = () => {};
const MyModule = {
doSomething: doSomething,
doAnotherThing: doAnotherThing
};
export default MyModule;
我有以下场景:
const doSomething = () => {
const test = 1;
doAnotherThing();
return test + 1;
};
const doAnotherThing = () => {};
module.exports = {
doSomething,
doAnotherThing
};
这是我的测试:
const MyModule = require('./myModule');
describe('MyModule', () => {
it('Should be able to spy another call', () => {
const spy = jest.spyOn(MyModule, 'doAnotherThing');
MyModule.doSomething();
expect(spy).toHaveBeenCalledTimes(1);
});
});
问题,有没有办法让 doSomething() 中的 doAnotherThing() 调用以某种方式被玩笑窥探,而不使用 rewire 等解决方案?
在此处找到解决方案:https://medium.com/welldone-software/jest-how-to-mock-a-function-call-inside-a-module-21c05c57a39f
为此重新定义了我的模块,现在可以使用了
const doSomething = () => {
const test = 1;
MyModule.doAnotherThing();
return test + 1;
};
const doAnotherThing = () => {};
const MyModule = {
doSomething: doSomething,
doAnotherThing: doAnotherThing
};
export default MyModule;