Node.js 使用Sinon、redux和Karma测试axios呼叫
您好,在redux测试文档中,他们有以下示例来测试api调用:Node.js 使用Sinon、redux和Karma测试axios呼叫,node.js,karma-runner,redux,sinon,nock,Node.js,Karma Runner,Redux,Sinon,Nock,您好,在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 mid
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。我不是异步操作方面的专家,因为在我的应用程序中,我单独测试了所有这些东西(操作创建者、使用nock模拟服务的API调用、异步行为,这要感谢redux文档中的代码如下所示
const store = mockStore({ todos: [] })
return store.dispatch(actions.fetchTodos())
.then(() => { // return of async actions
expect(store.getActions()).toEqual(expectedActions)
})
因此,分派将返回异步操作,并且您必须通过异步操作解析时将执行的函数中的测试。禁用端点应该可以正常工作。为此,您应该使用
例如:
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)
);
});
});
有什么更新吗?你解决了吗?