通过调用browserHistory测试async redux操作

时间:2016-12-06 13:48:14

标签: testing redux react-router

我遇到了测试异步redux操作(使用thunk)的问题,因为browserHistory未定义,因此会抛出错误。

(为简洁而修改的代码)

actions.js

import { browserHistory } from 'react-router'
import axios from 'axios'

export function foo() {
  return dispatch => {
    return axios.post('/foo')
      .then(res => { dispatch(something); browserHistory.push('/') })
      .catch(err => { dispatch(somethingError) }
  }
}

测试/ actions.js

import nock from 'nock'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'

const mockStore = configureMockStore([thunk])

describe('foo succeeds', () => {
  nock('localhost:300')
    .post('/foo')
    .reply(200)

  const store = mockStore()

  return store.dispatch(actions.foo())
    .then(expect(store.getActions()).to.equal(something))
})

这当然会导致TypeError: Cannot read property 'push' of undefined,这会提示未经处理的承诺拒绝。有什么方法可以模拟browserHistory或在测试中优雅地处理错误吗?

1 个答案:

答案 0 :(得分:3)

原来是一个简单的修复。在您的测试文件中,您可以模拟react-router:

import * as router from 'react-router'

router.browserHistory = { push: () => {} }