Chr*_*kai 6 javascript unit-testing redux redux-thunk
测试此功能的最佳方法是什么
export function receivingItems() {
return (dispatch, getState) => {
axios.get('/api/items')
.then(function(response) {
dispatch(receivedItems(response.data));
});
};
}
Run Code Online (Sandbox Code Playgroud)
这是我现在拥有的
describe('Items Action Creator', () => {
it('should create a receiving items function', () => {
expect(receivingItems()).to.be.a.function;
});
});
Run Code Online (Sandbox Code Playgroud)
Dan*_*mov 11
来自Redux "书写测试"的秘诀:
对于使用Redux Thunk或其他中间件的异步操作创建者,最好完全模拟Redux存储以进行测试.您仍然可以使用
applyMiddleware()模拟商店,如下所示(您可以在redux-mock-store中找到以下代码).您还可以使用nock来模拟HTTP请求.Run Code Online (Sandbox Code Playgroud)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))) } }可以测试如下:
Run Code Online (Sandbox Code Playgroud)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()) }) })