如何在开玩笑测试中比较(匿名)功能?

时间:2017-09-22 15:53:22

标签: javascript reactjs react-redux jestjs

我将以下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 操作在解析axios承诺时返回一个匿名方法。

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 ,我的测试失败了,因为istanbul在我的操作中添加了文本。输出如下:

 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 方法进行比较。在jest测试中比较(匿名)函数的正确方法是什么?

可在https://github.com/wvanvlaenderen/react-redux-weathercomponent

找到完整来源

2 个答案:

答案 0 :(得分: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();
  })

})

答案 1 :(得分:0)

使用Jest测试redux thunk时,我使用了expect.any(Function)。所有的断言库都有这样的内容。

ex)

动作

const toggleFilter = (toggle, isShown) => {
  return dispatch => {
    toggle === 'TOGGLE ONE'
      ? dispatch(toggleSwitchOne(isShown))
      : dispatch(toggleSwitchTwo(isShown));
  };
};

测试文件:

beforeEach(() => {
store = mockStore({ showFruit: false, showVeg: false });
      dispatch = jest.fn();
      getState = () => store;
})

it('will dispatch action to toggle switch', () => {
  let res = toggleFilter(type, isShown)(dispatch, getState);
  expect(dispatch).toHaveBeenCalledTimes(1);
  expect(dispatch).toHaveBeenCalledWith(expect.any(Function));
});