与Sinon一起testingaxios调用,还有redux和Karma

你好在testing的redux文档中,他们有这个例子来testingAPI调用:

import configureMockStore from 'redux-mock-store' import thunk from 'redux-thunk' import * as actions from '../../actions/counter' import * as types from '../../constants/ActionTypes' import nock from 'nock' const middlewares = [ thunk ] const mockStore = configureMockStore(middlewares) 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, { body: { 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()) }) }) 

我使用业力testing环境,我想我不能用nock来testing这个。 所以我正在考虑用Sinon来testing它。 麻烦是我不明白我将如何testing,因为我没有传递一个callback到我的API函数调用。 我正在使用axios来调用我的外部API。

为此,你应该使用axios-mock-adapter

例:

 import MockAdapter from 'axios-mock-adapter'; import axios from 'axios'; import thunk from 'redux-thunk'; import configureMockStore from 'redux-mock-store'; import * as actionTypes from './userConstants'; import * as actions from './userActions'; const mockAxios = new MockAdapter(axios); const mockStore = configureMockStore(middlewares); describe('fetchCurrentUser', () => { afterEach(() => { mockAxios.reset(); }); context('when request succeeds', () => { it('dispatches FETCH_CURRENT_USER_SUCCESS', () => { mockAxios.onGet('/api/v1/user/current').reply(200, {}); const expectedActions = [ { type: actionTypes.SET_IS_FETCHING_CURRENT_USER }, { type: actionTypes.FETCH_CURRENT_USER_SUCCESS, user: {} } ]; const store = mockStore({ users: Map() }); return store.dispatch(actions.fetchCurrentUser()).then(() => expect(store.getActions()).to.eql(expectedActions) ); }); }); 

我不是asynchronous操作的专家,因为在我的应用程序中,我分别testing所有这些东西(动作创build者,nock嘲笑服务的api调用,asynchronous行为感谢saga ,但是在redux文档中代码看起来像这样

  const store = mockStore({ todos: [] }) return store.dispatch(actions.fetchTodos()) .then(() => { // return of async actions expect(store.getActions()).toEqual(expectedActions) }) 

所以调度返回你的asynchronous行为,你必须通过testing在你的asynchronous行动解决时将被执行的函数。 停止端点应该可以正常工作。