2016-03-01 98 views
10

你好了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()) 
    }) 
}) 

我使用的是業力測試環境,我想我可以不要用諾克來測試這個。所以我正在考慮用Sinon來測試它。麻煩是我不明白我將如何測試使用這個,因爲我沒有傳遞迴調到我的API函數調用。我使用axios來調用我的外部API。

+0

對此有什麼更新?你設法解決它嗎? – anoop

回答

1

因爲在我的應用程序中,我不是專家,因爲在我的應用程序中我分別測試所有這些東西(動作創建者,API調用nock嘲笑服務,異步行爲感謝saga,但是在redux文檔中代碼看起來像這樣

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

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

於是派遣返回你的異步操作,你必須在將要執行的,當你異步操作會解決。Nock'ing端點應該只是罰款功能通過檢測。

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) 
    ); 
    }); 
    });