2016-08-17 106 views
3

我使用Enzyme來測試我的反應和redux部分。我已經閱讀並發現它也是編寫組件集成測試的良好實踐。 所以,這很簡單,因爲我必須調用動作創建者並根據商店檢查其更新的值,但我有一些異步操作返回dispatch操作。React-redux:如何編寫集成測試

login.actions.js

export function loginUser(credentials) { 
    return dispatch => { 
    dispatch(action.loginRequest()); 
    return axios({ 
     method: 'post', 
     url: `${api}/login`, 
     data: { 
     email: _.trim(_.get(credentials, 'email')), 
     password: _.get(credentials, 'password') 
     } 
    }) 
     .then(response => { 
     const { data } = response; 

     if (_.isEqual(_.get(response, 'status'), 200)) { 
      dispatch(action.loginSuccess(data)); 
     } 
     }) 
     .catch(err => { 
     dispatch(action.loginError(err)); 
     }); 
    }; 
} 

login.actionCreators.js

export function loginRequest() { 
    return { 
    type: types.LOGIN_REQUEST 
    }; 
} 
export function loginSuccess(payload) { 
    return { 
    type: types.LOGIN_SUCCESS, 
    payload 
    }; 
} 
export function loginError(payload) { 
    let error; 
    switch (_.get(payload, 'response.status')) { 
    case 422: { 
     error = 'Invalid Credentials'; 
     break; 
    } 
    case 401: { 
     error = 'Invalid user'; 
     break; 
    } 
    case 403: { 
     error = 'Account not confirmed'; 
     break; 
    } 
    default: 
     error = 'Something went wrong'; 
    } 
    return { 
    type: types.LOGIN_ERROR, 
    error 
    }; 
} 

因此,爲了執行一個完整的集成測試,我會測試login.actions.js以及由於派遣通常返回普通對象,在我的情況下,他們正在返回一個派遣函數。我如何測試它們?

回答

5

測試異步操作很簡單。我正在使用moxios ans sinon。你基本上可以擴展到所有不同的情況下,並在相同的模式下測試它

import moxios from 'moxios'; 
import configureMockStore from 'redux-mock-store'; 
import thunk from 'redux-thunk'; 
import { spy } from 'sinon'; 

const middlewares = [thunk]; 
const mockStore = configureMockStore(middlewares); 

describe('async actions',() => { 
    beforeEach(() => { 
    moxios.install(); 
    }); 

    afterEach(() => { 
    moxios.uninstall(); 
    }); 
    it(`should create action LOGIN_SUCCESS after successful login`,() => { 
    moxios.wait(() => { 
     const request = moxios.requests.mostRecent(); 
     request.respondWith({ 
     status: 200, 
     response: { message: 'success', status: '200' }, 
     }); 
    }); 
    const expectedActions = [ 
     { type: types.LOGIN_REQUEST }, 
     { type: types.LOGIN_SUCCESS, data: { message: 'success', status: '200' } }, 
    ]; 
    const store = mockStore({ auth: {} }); 
    return store.dispatch(loginUser('abcd', '1234')) 
    .then(() => { 
     expect(store.getActions()).to.eql(expectedActions); 
    }); 
    }); 
}); 
+0

如果遵循相同的情況,我要測試存儲中的狀態是否已更新? – Umair

+0

你正在這裏的商店測試,看看這裏使用的'mockstore' – anoop

+0

啊錯過了。 – Umair

相關問題