【问题标题】:Testing async redux action with call to browserHistory通过调用 browserHistory 测试异步 redux 操作
【发布时间】:2017-04-21 04:25:10
【问题描述】:

我在测试引发错误的异步 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) }
  }
}

test/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 或在测试中优雅地处理错误?

【问题讨论】:

    标签: testing redux react-router


    【解决方案1】:

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

    import * as router from 'react-router'
    
    router.browserHistory = { push: () => {} }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-03
      • 2017-10-14
      • 2017-03-04
      • 2019-10-31
      • 2017-01-26
      • 1970-01-01
      • 2019-11-12
      相关资源
      最近更新 更多