![](/img/trans.png)
[英]How to chain async actions and wait for the result without store.dispatch
[英]`TypeError: store.dispatch(…).then is not a function` when trying to test async actions
尝试使用以下示例测试我的异步操作创建者: http : //redux.js.org/docs/recipes/WritingTests.html#async-action-creators ,我想我做了所有相同的事情,但出现错误:
async actions › creates FETCH_BALANCE_SUCCEESS when fetching balance has been done
TypeError: store.dispatch(...).then is not a function
不明白为什么会发生这种情况,因为我一步一步地从示例中完成了所有操作。
我也找到了这个例子http://arnaudbenard.com/redux-mock-store/但无论如何,错误存在于某处,不幸的是,我找不到它。 我的错误在哪里,为什么即使我的测试用例看起来与示例相同
我的测试用例:
import nock from 'nock';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import * as actions from './';
import * as types from '../constants';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe('async actions', () => {
afterEach(() => {
nock.cleanAll();
});
it('creates FETCH_BALANCE_SUCCEESS when fetching balance has been done', () => {
const store = mockStore({});
const balance = {};
nock('http://localhost:8080')
.get('/api/getbalance')
.reply(200, { body: { balance } });
const expectedActions = [
{ type: types.FETCH_BALANCE_REQUEST },
{ type: types.FETCH_BALANCE_SUCCEESS, body: { balance } },
];
return store.dispatch(actions.fetchBalanceRequest()).then(() => {
// return of async actions
expect(store.getActions()).toEqual(expectedActions);
});
});
});
我正在尝试测试的我的行为。
import 'whatwg-fetch';
import * as actions from './actions';
import * as types from '../constants';
export const fetchBalanceRequest = () => ({
type: types.FETCH_BALANCE_REQUEST,
});
export const fetchBalanceSucceess = balance => ({
type: types.FETCH_BALANCE_SUCCEESS,
balance,
});
export const fetchBalanceFail = error => ({
type: types.FETCH_BALANCE_FAIL,
error,
});
const API_ROOT = 'http://localhost:8080';
const callApi = url =>
fetch(url).then(response => {
if (!response.ok) {
return Promise.reject(response.statusText);
}
return response.json();
});
export const fetchBalance = () => {
return dispatch => {
dispatch(actions.fetchBalanceRequest());
return callApi(`${API_ROOT}/api/getbalance`)
.then(json => dispatch(actions.fetchBalanceSucceess(json)))
.catch(error =>
dispatch(actions.fetchBalanceFail(error.message || error))
);
};
};
在你的测试中,你有
return store.dispatch(actions.fetchBalanceRequest()).then(() => { ... })
您正在尝试测试fetchBalanceRequest
,它返回一个对象,因此您不能对此调用.then()
。 在您的测试中,您实际上想要测试fetchBalance
,因为它是一个异步操作创建者(这就是您发布的 redux 文档中的解释)。
这通常是 redux-mock-store 的问题
请记住:
从“redux-mock-store”导入 configureStore
函数 configureStore 不返回一个有效的商店,而是一个工厂。
这意味着您必须致电工厂才能获得商店:
const store = configureStore([])()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.