你好,在 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())
})
})
我正在使用 karma 测试环境,我想我不能使用 nock 来测试它。所以我正在考虑使用 Sinon 来测试它。问题是我不明白如何使用它进行测试,因为我没有将回调传递给我的 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)
);
});
});
关于node.js - 使用 Sinon、redux 和 Karma 测试 axios 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35722027/