Testing 通过调用browserHistory测试异步redux操作
我在测试异步redux操作(使用thunk)时遇到了一个问题,该操作会抛出一个错误,因为Testing 通过调用browserHistory测试异步redux操作,testing,redux,react-router,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
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) }
}
}
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))
})
test/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) }
}
}
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))
})
这当然会导致
类型错误:无法读取未定义的的属性“push”,这会提示未处理的承诺拒绝。有没有什么方法可以模拟浏览器历史记录
或优雅地处理测试中的错误?结果证明是一个简单的修复方法。在测试文件中,您可以模拟react路由器:
import * as router from 'react-router'
router.browserHistory = { push: () => {} }
结果是一个简单的解决方案。在测试文件中,您可以模拟react路由器:
import * as router from 'react-router'
router.browserHistory = { push: () => {} }