javascript - 测试调用 API 的 redux 操作

标签 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;
  });
});

最佳答案

来自 Redux “Writing Tests”食谱:

For async action creators using Redux Thunk or other middleware, it’s best to completely mock the Redux store for tests. You can still use applyMiddleware() with a mock store, as shown below (you can find the following code in redux-mock-store). You can also use nock to mock the HTTP requests.

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)))
  }
}

can be tested like:

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())
  })
})

关于javascript - 测试调用 API 的 redux 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33794629/

相关文章:

javascript - JavaScript 中可用的最大日期

java - Spring框架在测试应用方面有哪些优势?

unit-testing - 如何在 NUUnit 中测试私有(private)变量?

javascript - Spring MVC - 从数据库向 Google map 添加多个标记

javascript - 在不影响背景的情况下删除图像 Canvas 上的线条

javascript - 选择要为函数传递的参数。 Javascript

C#:保护级别错误

javascript - 当使用 redux saga 和 React 时,状态如何在 sagas.js 中获取

javascript - react 和 Jest : Cannot find module from test file

javascript - 合并嵌套对象而不发生变异