我正在使用Jest
并moxios
为我的异步函数编写测试:
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 生成的代码覆盖率报告时,它显示该then
块getData
未被覆盖/调用。我怎样才能解决这个问题?