我正在使用Jest.js测试生成器函数,但我的问题通常是模拟模块中的函数。
Foo.js有: -
const Foo = {
callMe() {
return true;
},
callMe2() {
return true;
}
};
export default Foo;
在我的Jest测试中,我希望Foo.callMe
抛出一个错误,但我不能让它与Jest mock一起工作。
import Foo from '../Foo';
it('fails my generator function', () => {
const gen = myGenFunction();
expect(gen.next().value).toEqual(call(Foo.callMe));
});
生成器函数看起来像这样:
export function* myGenFunction(action) {
try {
const response = yield call(Foo.callMe);
console.log('Success');
} catch(err) {
console.log('Error!!!');
} finally {
// do something else
}
}
如何让Foo.callMe
抛出错误?我尝试了一些东西,但迄今为止没有任何效果。
我已经设法通过使用redux-saga的throw方法实现了我想要的。
it('fails my generator function', () => {
const error = { message: 'Look see here, an error' };
const gen = myGenFunction();
...
expect(gen.throw(error).value).toEqual(
put(actions.setIsLoading(false)), // action that happens on fail
'gen should yield an Effect put(actions.setIsLoading(false))'
);
});
这里有很好的记录:https://redux-saga.js.org/docs/basics/ErrorHandling.html