2017-09-22 1 views
0

다음과 같은 React 구성 요소가 redux 저장소에 연결되어 있습니다.농담 테스트에서 (익명) 기능을 비교하는 방법?

import React, { Component } from 'react' 
import logo from './logo.svg' 
import './App.css' 
import { connect } from 'react-redux' 
import { getWeather } from './actions/WeatherActions' 
import WeatherComponent from './components/weatherComponent/WeatherComponent' 
import { get } from 'lodash' 

export class App extends Component { 

    componentDidMount() { 
    this.props.dispatch(getWeather()) 
    } 

    render() { 
    return (
     <div className="App"> 
      <div className="App-header"> 
      <img src={logo} className="App-logo" alt="logo" /> 
      <h2>Welcome to React</h2> 
      </div> 
      <WeatherComponent 
       weather={{ 
       location: get(this.props.weatherReducer.weather, 'name'), 
       temp: get(this.props.weatherReducer.weather, 'main.temp') 
       }} 
      /> 
     </div> 
    ) 
    } 
} 

export default connect((store) => { 
    return { 
    weatherReducer: store.weatherReducer, 
    } 
})(App) 

컴포넌트는 componentDidMount 콜백을 사용 getWeather 동작을 디스패치한다. getWeather 작업은 액시스 약속을 해결할 때 익명 메소드를 반환합니다.

import { GET_WEATHER_DONE, GET_WEATHER_ERROR } from './ActionTypes' 
import axios from 'axios' 

export function getWeather() { 
    let endpoint = 'http://api.openweathermap.org/data/2.5/weather?q=London&appid=2a345681ddcde393253af927097f5747' 

    return function (dispatch) { 
    return axios.get(endpoint) 
    .then((response) => { 
     return dispatch({ 
     type: GET_WEATHER_DONE, 
     payload: response.data 
     }) 
    }) 
    .catch((error) => { 
     return dispatch({ 
     type: GET_WEATHER_ERROR, 
     payload: error.response.data, 
     statuscode: error.response.status 
     }) 
    }) 
    } 
} 

나는 getWeather 조치를 확인하는 단위 테스트를 작성하는 것을 시도하고 아니오 설치에 파견되고 있지 않습니다. 이 테스트는 다음과 같이 보입니다. 작업의 익명 메소드를 반환하기 때문에

import React from 'react' 
import ReactDOM from 'react-dom' 
import App from './App' 
import configureMockStore from 'redux-mock-store' 
import thunk from 'redux-thunk' 
import * as actions from './actions/WeatherActions' 

describe('app container',() => { 
    const store = configureMockStore([thunk])({ 
    weatherReducer: { 
     weather: {} 
    } 
    }) 

    const dispatchSpy = jest.fn() 
    store.dispatch = dispatchSpy 

    it('dispatches getWeather() action upon rendering',() => { 
    ReactDOM.render(<App store={store} />, document.createElement('div')) 

    expect(dispatchSpy.mock.calls[0][0].toString()).toEqual(actions.getWeather().toString()) 
    }) 

}) 

, 나는 행동을 비교하는 내 모의시 toString 메소드를 호출 할 필요가있다.

스냅 샷 테스트를 사용하여이 테스트를 다시 작성했습니다.

import React from 'react' 
import ReactDOM from 'react-dom' 
import App from './App' 
import configureMockStore from 'redux-mock-store' 
import thunk from 'redux-thunk' 

describe('app container',() => { 
    const store = configureMockStore([thunk])({ 
    weatherReducer: { 
     weather: {} 
    } 
    }) 

    const dispatchSpy = jest.fn() 
    store.dispatch = dispatchSpy 

    it('dispatches correct actions upon rendering',() => { 
    ReactDOM.render(<App store={store} />, document.createElement('div')) 

    let tree = dispatchSpy.mock.calls.toString() 
    expect(tree).toMatchSnapshot(); 
    }) 


}) 

는 다시 나는 다음과 같은 스냅 샷의 결과로, toString 메소드를 호출 할 필요가있다. 실 테스트를 사용하여 범위를 실행할 때

// Jest Snapshot v1, 

exports[`app container dispatches correct actions upon rendering 1`] = ` 
"function (dispatch) { 
    return _axios2.default.get(endpoint). 
    then(response => { 
     return dispatch({ 
     type: _ActionTypes.GET_WEATHER_DONE, 
     payload: response.data }); 

    }). 
    catch(error => { 
     return dispatch({ 
     type: _ActionTypes.GET_WEATHER_ERROR, 
     payload: error.response.data, 
     statuscode: error.response.status }); 

    }); 
    }" 
`; 

지금 - --coverage, 내 테스트는 내 행동에 텍스트를 추가하기 때문에 이스탄불의 실패합니다. 출력은 다음과 같습니다

FAIL src/App.snapshot.test.js 
    ● app container › dispatches correct actions upon rendering 

    expect(value).toMatchSnapshot() 

    Received value does not match stored snapshot 1. 

    - Snapshot 
    + Received 

    -"function (dispatch) { 
    - return _axios2.default.get(endpoint). 
    - then(response => { 
    -  return dispatch({ 
    -  type: _ActionTypes.GET_WEATHER_DONE, 
    -  payload: response.data }); 
    +"function (dispatch) {/* istanbul ignore next */cov_2rypo7bhf.f[1]++;cov_2rypo7bhf.s[2]++; 
    + return (/* istanbul ignore next */_axios2.default.get(endpoint). 
    +  then(response => {/* istanbul ignore next */cov_2rypo7bhf.f[2]++;cov_2rypo7bhf.s[3]++; 
    +  return dispatch({ 
    +   type: /* istanbul ignore next */_ActionTypes.GET_WEATHER_DONE, 
    +   payload: response.data }); 

    - }). 
    - catch(error => { 
    -  return dispatch({ 
    -  type: _ActionTypes.GET_WEATHER_ERROR, 
    -  payload: error.response.data, 
    -  statuscode: error.response.status }); 
    +  }). 
    +  catch(error => {/* istanbul ignore next */cov_2rypo7bhf.f[3]++;cov_2rypo7bhf.s[4]++; 
    +  return dispatch({ 
    +   type: /* istanbul ignore next */_ActionTypes.GET_WEATHER_ERROR, 
    +   payload: error.response.data, 
    +   statuscode: error.response.status }); 

    - }); 
    +  })); 
     }" 

     at Object.it (src/App.snapshot.test.js:21:18) 
     at Promise.resolve.then.el (node_modules/p-map/index.js:46:16) 

내가 직면하고 주요 문제는 내가 비교를 위해 toString 메소드를 호출 할 필요가 있다는 사실이다. 농담 테스트에서 (익명) 기능을 비교하는 올바른 방법은 무엇입니까?

전체 소스는 https://github.com/wvanvlaenderen/react-redux-weathercomponent

+0

테스트에서'toString' 캐스트에 의존하지 마십시오. 코드를 테스트 코드에 쉽게 연결할 수있는 방식으로 코드를 작성하십시오. – Halcyon

+1

'componentDidMount'에'dispatch'를 호출하는 것을 보았습니다 만,'dispatch'를 사용하여 어떻게'getWeather'를할까요? 스냅 샷 테스트를 수행하는 것이 너무 이른 것 같습니다. 대신'dispatch'가 올바른 액션으로 호출되는지 확인해야합니다 –

답변

0

에서 찾을 수 있습니다 그래서 난 내 시험에서 getWeather 조치를 조롱하고, 개별 통화에 대한 반환 값의 유형을 확인하여 파견에 수 테스트 호출했다.

import React from 'react' 
import ReactDOM from 'react-dom' 
import App from './App' 
import configureMockStore from 'redux-mock-store' 
import thunk from 'redux-thunk' 
import * as actions from './actions/WeatherActions' 
import { spy } from 'sinon' 

describe('app container',() => { 
    const store = configureMockStore([thunk])({ 
    weatherReducer: { 
     weather: {} 
    } 
    }) 

    const dispatchSpy = spy(store, 'dispatch') 

    actions.getWeather = jest.fn().mockImplementation(() => { 
    return {type: 'fetching weather'} 
    }) 

    it('dispatches getWeather() action upon rendering',() => { 
    ReactDOM.render(<App store={store} />, document.createElement('div')) 

    expect(dispatchSpy.firstCall.returnValue.type).toEqual('fetching weather') 
    }) 

}) 

디스패치 스파이에서 호출 트리를 렌더링하여 스냅 샷 테스트를 수행했습니다.

import React from 'react' 
import ReactDOM from 'react-dom' 
import App from './App' 
import { spy } from 'sinon' 
import configureMockStore from 'redux-mock-store' 
import thunk from 'redux-thunk' 
import * as actions from './actions/WeatherActions' 

describe('app container',() => { 
    const store = configureMockStore([thunk])({ 
    weatherReducer: { 
     weather: {} 
    } 
    }) 

    const dispatchSpy = spy(store, 'dispatch') 

    actions.getWeather = jest.fn().mockImplementation(() => { 
    return {type: 'fetching weather'} 
    }) 

    it('dispatches correct actions upon rendering',() => { 
    ReactDOM.render(<App store={store} />, document.createElement('div')) 

    expect(dispatchSpy.getCalls()).toMatchSnapshot(); 
    }) 

})