【发布时间】:2019-07-05 07:18:29
【问题描述】:
我已经使用 react、redux-mock-store 和 redux 编写了测试用例,但我不断出错。我在 stackoverflow 上检查了同样的错误,但我无法理解。
Cannot read property '.then' of undefined when testing async action creators with redux and react
这是我的 index.js 文件:
import { post } from '../../../service/index';
import { CREATE_JD_SUCCESS, CREATE_JD_FAILED, CREATE_JD_URL, REQUEST_INITIATED, REQUEST_SUCCESSED } from '../../../constants/AppConstants'
export function createJob(jd) {
return (dispatch) => {
dispatch({
type: REQUEST_INITIATED
});
post(CREATE_JD_URL, jd)
.then((response) => {
if (response.status === 200) {
dispatch({
type: REQUEST_SUCCESSED,
});
dispatch({
type: CREATE_JD_SUCCESS,
data: response.payload,
})
}
else {
dispatch({
type: REQUEST_SUCCESSED
});
dispatch({
type: CREATE_JD_FAILED,
data: response.status,
});
}
})
}
}
这是我的 index.test.js 文件
import * as actions from '../index';
import configureMockStore from 'redux-mock-store';
import moxios from 'moxios';
import thunk from 'redux-thunk';
import apiGatewayEndpoint from '../../../../config/index';
import { CREATE_JD_SUCCESS, CREATE_JD_URL } from '../../../../constants/AppConstants';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
const newJd = {
"companyId": "12345",
"jobDescription": 'Hello there'
};
const responseData = "job created!";
describe('actions for creating new job', () => {
beforeEach(function () {
moxios.install();
});
afterEach(function () {
moxios.uninstall();
});
it('action for create job', async (done) => {
let url = CREATE_JD_URL;
moxios.stubRequest(apiGatewayEndpoint.apiGatewayEndpoint + url, {
status: 200,
response: responseData
});
const expectedActions = [{ "type": "REQUEST_INITIATED" }, { "type": "REQUEST_SUCCESSED" }, { data: responseData, type: "CREATE_JD_SUCCESS" }];
const store = mockStore({});
await store.dispatch(actions.createJob(newJd))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
done();
});
});
在回答的上述链接上,他说错误即将到来是因为 store.dispatch() 方法返回 undefined.bt 在我的情况下,我的其他操作测试用例运行良好,这与我上面写的相同不知道为什么收到此错误。
运行 npm test 时出现控制台错误:
● actions for creating new jd › action for create jd
TypeError: Cannot read property 'then' of undefined
38 | const expectedActions = [{ "type": "REQUEST_INITIATED" }, { "type": "REQUEST_SUCCESSED" }, { data: responseData, type: "CREATE_JD_SUCCESS" }];
39 | const store = mockStore({});
> 40 | await store.dispatch(actions.createJob(newJd))
| ^
41 | .then(() => {
42 | expect(store.getActions()).toEqual(expectedActions);
43 | });
如果有人知道,请指导我在这里做错了什么。任何帮助将不胜感激
【问题讨论】:
标签: reactjs unit-testing jestjs enzyme redux-thunk