gpt4 book ai didi

通过调用 browserHistory 测试异步 redux 操作

转载 作者:行者123 更新时间:2023-11-28 21:04:16 24 4
gpt4 key购买 nike

我在测试异步 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,提示未处理的 promise 拒绝。有什么方法可以模拟 browserHistory 或在测试中优雅地处理错误?

最佳答案

事实证明这是一个简单的修复。在您的测试文件中,您可以模拟 react-router:

import * as router from 'react-router'

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

关于通过调用 browserHistory 测试异步 redux 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40996922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com