[英]Code coverage not working for Jest test with Axios
我正在使用Jest
和moxios
为我的异步 function 编写测试:
export function getData(id) {
return dispatch => {
return axios({
method: "get",
url: `${'url'}/id`
})
.then(response => {
dispatch(setData(response.data));
})
.catch(() => alert('Could not fetch data');
};
}
测试:
import configureMockStore from "redux-mock-store";
import thunk from "redux-thunk";
import moxios from "moxios";
import getData from '../redux/getData';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const store = mockStore({});
describe('Test fetch data', () => {
beforeEach(function() {
moxios.install();
store.clearActions();
});
afterEach(function() {
moxios.uninstall();
});
it('should fetch data and set it', () => {
const data = [{ name: 'John', profession: 'developer'}];
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: data
});
const expectedActions = [setData(data)];
return store.dispatch(getData()).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
})
})
我的测试通过了,但是当我检查 Jest 生成的代码覆盖率报告时,它显示getData
的then
块没有被覆盖/调用。 我怎样才能解决这个问题?
moxios.wait
return Promise
你的测试 function 在运行之前返回except
函数。
您需要在测试中使用done
回调 function
it('should fetch data and set it', (done) => {
const data = [{
name: 'John',
profession: 'developer'
}];
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200,
response: data
});
const expectedActions = [setData(data)];
store.dispatch(getData()).then(() => {
expect(store.getActions()).toEqual(expectedActions);
done();
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.