这是我的异步操作,涉及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
。感谢您的帮助。
答案 0 :(得分:1)
您的操作没有返回任何承诺,因此您可以使用then
在测试用例中处理它。
您需要在调用return
之前将axios
语句添加到操作中。
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: []
});
});
};
我面临着同样的问题,并且我以这种方式解决了!