测试调用API的redux操作

时间:2015-11-19 03:15:51

标签: javascript unit-testing redux redux-thunk

测试此功能的最佳方法是什么

export function receivingItems() {
  return (dispatch, getState) => {
    axios.get('/api/items')
      .then(function(response) {
        dispatch(receivedItems(response.data));
      });
  };
}

这是我目前所拥有的

describe('Items Action Creator', () => {
  it('should create a receiving items function', () => {
    expect(receivingItems()).to.be.a.function;
  });
});

2 个答案:

答案 0 :(得分:11)

来自Redux “Writing Tests”食谱:

  

对于使用Redux Thunk或其他中间件的异步操作创建者,最好完全模拟Redux存储以进行测试。您仍然可以将applyMiddleware()与模拟商店一起使用,如下所示(您可以在redux-mock-store中找到以下代码)。您还可以使用nock模拟HTTP请求。

function fetchTodosRequest() {
  return {
    type: FETCH_TODOS_REQUEST
  }
}

function fetchTodosSuccess(body) {
  return {
    type: FETCH_TODOS_SUCCESS,
    body
  }
}

function fetchTodosFailure(ex) {
  return {
    type: FETCH_TODOS_FAILURE,
    ex
  }
}

export function fetchTodos() {
  return dispatch => {
    dispatch(fetchTodosRequest())
    return fetch('http://example.com/todos')
      .then(res => res.json())
      .then(json => dispatch(fetchTodosSuccess(json.body)))
      .catch(ex => dispatch(fetchTodosFailure(ex)))
  }
}
     

可以测试如下:

import expect from 'expect'
import { applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import * as actions from '../../actions/counter'
import * as types from '../../constants/ActionTypes'
import nock from 'nock'

const middlewares = [ thunk ]

/**
 * Creates a mock of Redux store with middleware.
 */
function mockStore(getState, expectedActions, done) {
  if (!Array.isArray(expectedActions)) {
    throw new Error('expectedActions should be an array of expected actions.')
  }
  if (typeof done !== 'undefined' && typeof done !== 'function') {
    throw new Error('done should either be undefined or function.')
  }

  function mockStoreWithoutMiddleware() {
    return {
      getState() {
        return typeof getState === 'function' ?
          getState() :
          getState
      },

      dispatch(action) {
        const expectedAction = expectedActions.shift()

        try {
          expect(action).toEqual(expectedAction)
          if (done && !expectedActions.length) {
            done()
          }
          return action
        } catch (e) {
          done(e)
        }
      }
    }
  }

  const mockStoreWithMiddleware = applyMiddleware(
    ...middlewares
  )(mockStoreWithoutMiddleware)

  return mockStoreWithMiddleware()
}

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll()
  })

  it('creates FETCH_TODOS_SUCCESS when fetching todos has been done', (done) => {
    nock('http://example.com/')
      .get('/todos')
      .reply(200, { todos: ['do something'] })

    const expectedActions = [
      { type: types.FETCH_TODOS_REQUEST },
      { type: types.FETCH_TODOS_SUCCESS, body: { todos: ['do something']  } }
    ]
    const store = mockStore({ todos: [] }, expectedActions, done)
    store.dispatch(actions.fetchTodos())
  })
})

答案 1 :(得分:2)

我会使用存根axios(例如使用mock-require)并编写一个实际调用receivingItems()(dispatch, getState)的测试,并确保使用正确的数据调用dispatch