我对Jest很陌生,不可否认我是测试异步代码的专家......
我有一个简单的Fetch帮手:
export function fetchHelper(url, opts) {
return fetch(url, options)
.then((response) => {
if (response.ok) {
return Promise.resolve(response);
}
const error = new Error(response.statusText || response.status);
error.response = response;
return Promise.reject(error);
});
}
Run Code Online (Sandbox Code Playgroud)
并像这样实现它:
export function getSomeData() {
return (dispatch) => {
return fetchHelper('http://datasource.com/').then((res) => {
dispatch(setLoading(true));
return res.json();
}).then((data) => {
dispatch(setData(data));
dispatch(setLoading(false));
}).catch(() => {
dispatch(setFail());
dispatch(setLoading(false));
});
};
}
Run Code Online (Sandbox Code Playgroud)
但是,我想测试在正确的情况下以正确的顺序触发正确的调度.
这曾经很容易用a sinon.spy(),但我无法弄清楚如何在Jest中复制它.理想情况下,我希望我的测试看起来像这样:
expect(spy.args[0][0]).toBe({
type: SET_LOADING_STATE,
value: true,
});
expect(spy.args[1][0]).toBe({
type: SET_DATA,
value: {...},
}); …Run Code Online (Sandbox Code Playgroud)