用Sinon测试axios调用,使用redux和Karma

Bob*_*bby 10 node.js sinon karma-runner nock redux

你好在redux文档中进行测试,他们有这个例子来测试api调用:

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())
  })
})
Run Code Online (Sandbox Code Playgroud)

我正在使用业力测试环境,我想我不能用nock来测试这个.所以我正在考虑使用Sinon进行测试.麻烦是我不明白我将如何测试使用它,因为我没有将回调传递给我的api函数调用.我正在使用axios来调用我的外部API.

Sam*_*amo 5

为此,您应该使用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)
      );
    });
  });
Run Code Online (Sandbox Code Playgroud)


Mad*_*Nat 1

我不是异步操作方面的专家,因为在我的应用程序中,我单独测试了所有这些东西(操作创建者、使用 nock 模拟服务的 api 调用、得益于saga 的异步行为,但是在 redux 文档中代码看起来像这样

    const store = mockStore({ todos: [] })

    return store.dispatch(actions.fetchTodos())
      .then(() => { // return of async actions
        expect(store.getActions()).toEqual(expectedActions)
      })
Run Code Online (Sandbox Code Playgroud)

因此,调度返回您的异步操作,并且您必须在异步操作解析时执行的函数中通过测试。对接端点应该可以正常工作。