【发布时间】:2021-02-02 10:10:06
【问题描述】:
我正在使用 axios 取消令牌在我的 useEffect 挂钩中进行清理,如下所示。当我运行测试时,我得到如下所示的错误。我正在使用反应测试库和开玩笑来测试我的应用程序。我也在使用模拟服务工作者来拦截和处理请求。有没有办法可以模拟 axios.CancelToken.source 调用来解决失败的测试?
UseEffect 钩子:
useEffect(() => {
const source = axios.CancelToken.source()
axios.get(URLS.GET_DATA,
{
cancelToken: source.token
})
.then(response => {
setData(response.data)
})
.catch((error) => {
if (axios.isCancel(error)) {
} else {
console.log('Handle Error')
}
})
return () => {
source.cancel()
}
}, [building, numberOfDeletions, numberOfUpdates, numberOfAdds], [])
测试服务器服务工作者:
const server = setupServer(
rest.get('/api/data/'), (req, res, ctx) => {
return res(
ctx.status(200),
ctx.json({ data: data })
)})
测试失败:
it('should render title to page', () => {
const { getByText } = render(<EditIndex />)
const heading = getByText('Edit Items')
expect(heading.textContent).toEqual('Edit Items')
})
错误信息:
【问题讨论】:
-
这个错误可能意味着你已经在模拟 Axios 但你没有显示这个。否则它将有
CancelToken。
标签: reactjs axios jestjs react-hooks react-testing-library