这是我的异步操作,涉及api调用和操作创建者
export const getPosts = () => (dispatch) => {
dispatch({ type: LOADING_DATA });
axios
.get(`/posts`)
.then(res => {
dispatch({
type: SET_POSTS,
payload: res.data
});
})
.catch(err => {
dispatch({
type: SET_POSTS,
payload: []
});
});
};
我正在测试当调用getPosts
时,它将调度LOADING_DATA,然后是SET_POSTS。
import axios from 'axios';
import moxios from 'moxios';
import expect from 'expect';
import thunk from 'redux-thunk';
import configureMockStore from 'redux-mock-store';
import { getPosts } from '../actions/dataActions';
import { LOADING_DATA, SET_POSTS } from '../actions/actionTypes';
describe('dataActions', () => {
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
beforeEach(() => {
moxios.install();
});
// getPosts - when calling LOADING_DATA, we dispatch SET_POSTS with expected payload
it('should dispatch an action to get posts', () => {
moxios.wait(() => {
const request = moxios.requests.mostRecent();
request.respondWith({
status: 200
});
});
const expectedActions = [
{ type: LOADING_DATA},
{ type: SET_POSTS}
]
const store = mockStore({ posts: [] })
return store.dispatch(getPosts()).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
})
afterEach(() => {
moxios.uninstall();
});
})
但是,我收到的是TypeError: Cannot read property 'then' of undefined
。我感谢你的帮助。
您的操作不会返回任何promise,以便您可以使用then
在测试用例中处理它
您需要在调用axios
之前将return
语句添加到操作中。
export const getPosts = () => (dispatch) => {
dispatch({ type: LOADING_DATA });
//Just add return statement
return axios
.get(`/posts`)
.then(res => {
dispatch({
type: SET_POSTS,
payload: res.data
});
})
.catch(err => {
dispatch({
type: SET_POSTS,
payload: []
});
});
};
我也面临着同样的问题,我就这样解决了!