2017-09-13 3 views
2

반응 :테스트 비동기 방법은 내가 단위 테스트에서 초보자 오전 2 개 파일이 농담

RestaurantReducer을

import * as Const from '../constants/Const' 

const RestaurantReducer = (state = { 
    restaurantList: [] 
}, action) => { 
    switch (action.type) { 
     case Const.GET_RESTAURANT_LIST: { 

      return { 
       ...state, 
       restaurantList: action.payload 
      }; 
     } 
    } 
    return state; 
}; 

export default RestaurantReducer; 

및 RestauntActions.js

export function getRestaurantList() { 
    return dispatch => { 
     axios({ 
      method: "GET", 
      url: URLS.URL_RESTAURANT_LIST 
     }).then((response) => { 

      dispatch({ 
       type: CONST.GET_RESTAURANT_LIST, 
       payload: response.data 
      }) 
     }) 
    } 
} 

내 시험 :

describe('request reducer',() => { 

it('Default values',() => { 
    expect(restReducer(undefined, {type: 'unexpected'})).toEqual({ 
     restaurantList: [] 
    }); 
}); 

//----------------Dont know how to checked this------------------- 
it('Async data',async() => { 

    expect(restReducer(undefined, { 
     type: 'GET_RESTAURANT_LIST', 
    })).toEqual({ 
     ...state, 
     restaurantList: [] 
    }); 
}); 
//----------------ASYNC TEST------------------- 
}); 

어떻게 해야할지 모르겠다. 그것에 대해 갈 것입니다. 서버에서 오는 연결 또는 데이터를 확인할 수 있습니까? 이러한 데이터는 시뮬레이션 할 수 있지만 동적입니다.

답변

0

당신이 당신의 의존성을 조롱 할 필요가있는 기본적인 생각 (경우에 따라 축사). This answer describe how to do that.

나는 아이디어를 설명하기 위해 샘플을 만들어 :

const axios = require('axios') 
const assert = require('assert') 
const moxios = require('moxios') 


const asyncFunctionToTest =() => { 
    // grabs length of google page body 
    return axios({ 
     url: 'http://google.com', 
     method: 'GET' 
    }) 
    .then(resp => resp.data.length) 
} 



describe('async function',() => { 
    beforeEach(function() { 
     // import and pass your custom axios instance to this method 
     moxios.install() 
    }) 

    afterEach(function() { 
     // import and pass your custom axios instance to this method 
     moxios.uninstall() 
    }) 
    it('returns propper body length',() => { 
     const BODY = 'short string' 
     const mocked = moxios.wait(function() { 
      const request = moxios.requests.mostRecent() 
      request.respondWith({ 
       status: 200, 
       response: BODY 
      }) 
     }) 
     return Promise.all([asyncFunctionToTest(), mocked]) // imported bit: you need to return promise somehow in your test 
      .then(([result]) => { 
       assert(result === BODY.length, result) 
      }) 
    }) 
}) 
+0

이 검사에만 Axios의 요청을하지만 난에서 전환이 작업은'RestaurantReducer'가 –

+1

, 내가 만들 샘플을 확인하시기 바랍니다 테스트를 싶어요. – kharandziuk

+0

@ ThePrzemyslaw94 그것을 테스트 할 수 있었습니까? 조언이 필요하십니까? – kharandziuk