gpt4 book ai didi

javascript - Jest.js 模拟模块中的方法

转载 作者:行者123 更新时间:2023-11-30 21:20:06 24 4
gpt4 key购买 nike

我正在使用 Jest.js 测试生成器函数,但我的问题通常是关于模块内的模拟函数。

Foo.js 有:-

const Foo = {
callMe() {
return true;
},
callMe2() {
return true;
}
};
export default Foo;

在我的 Jest 测试中,我希望 Foo.callMe 抛出一个错误,但我无法让它与 Jest 模拟一起工作。

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

关于javascript - Jest.js 模拟模块中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45280043/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com