我有一个通过axios发出API请求的redux-thunk动作创建器,然后该请求的结果决定了我的reducer(AUTH或UNAUTH)调度了什么类型的动作 .
这很有效,但我不确定测试此功能的正确方法 . 我已经到了下面的解决方案,但在我的测试中出现以下错误:
1) AUTH ACTION
returns a token on success:
TypeError: Cannot read property 'then' of undefined
现在这个错误让我相信我从我的行动创造者那里得到的回报并不是一个承诺,但我真的很难找到前进的方向 .
src/actions/index.js
import axios from "axios";
import { AUTH_USER } from "./types";
const ROOT_URL = "http://localhost:";
const PORT = "3030";
export function signinUser({ email, password }) {
return ((dispatch) => {
axios
.post(`${ROOT_URL}${PORT}/signin`, { email, password })
.then(response => {
// update state to be auth'd
dispatch({ type: AUTH_USER });
// Save token locally
localStorage.setItem('token', response.data.token)
})
.catch(error => {
dispatch({ type: AUTH_ERROR, payload: error });
});
});
}
test/actions/index_test.js
import { expect } from "../test_helper";
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import moxios from 'moxios';
import { AUTH_USER } from "../../src/actions/types";
import { signinUser } from "../../src/actions/index";
const middleware = [thunk];
const mockStore = configureMockStore(middleware);
let store;
let url;
describe('AUTH ACTION', () => {
beforeEach(() => {
moxios.install();
store = mockStore({});
url = "http://localhost:3030";
});
afterEach(() => {
moxios.uninstall();
});
it('returns a token on success', (done) => {
moxios.stubRequest(url, {
status: 200,
response: {
data: {
token: 'sample_token'
}
},
});
const expectedAction = { type: AUTH_USER }
let testData = { email: "test1@test.com", password: "1234"}
store.dispatch(signinUser(testData)).then(() => {
const actualAction = store.getActions()
expect(actualAction).to.eql(expectedAction)
})
})
})
任何帮助或见解将不胜感激 .
1 回答
store.dispatch(someThunk()).then()
仅在thunk返回一个promise时才有效,而你的thunk实际上并没有返回一个promise .如果你只是在
axios()
前放一个return
,它应该可以工作 .