`TypeError:store.dispatch(...)。然后在尝试测试异步操作时不是函数

时间:2017-06-23 09:37:26

标签: javascript reactjs redux react-redux

尝试使用此示例测试我的异步操作创建者: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))
      );
  };
};

2 个答案:

答案 0 :(得分:3)

在你的考试中你有

return store.dispatch(actions.fetchBalanceRequest()).then(() => { ... })

您正在尝试测试返回对象的fetchBalanceRequest,因此您无法在其上调用.then()。在您的测试中,您实际上想要测试fetchBalance,因为那是一个异步操作创建者(这就是您发布的redux文档中解释的内容)。

答案 1 :(得分:0)

这通常是redux-mock-store的问题

请记住:

从'redux-mock-store'导入configureStore

configureStore函数不会返回有效的商店,而是一个工厂。

这意味着您必须致电工厂才能获得商店:

const store = configureStore([])()

相关问题