本文介绍了Jest 快照测试错误:您不应使用 <Link>在 <Router> 之外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为我的 Footer
组件编写快照测试,但它抛出错误:You should not use 在
之外.这是我的代码:
I want to write snapshot test for my Footer
component, but it throws error: You should not use <Link> outside a <Router>
. Here is my code:
import React from 'react'
import renderer from 'react-test-renderer'
import Footer from '../footer'
it('Footer renders correctly', () => {
const tree = renderer
.create(<Footer />)
.toJSON()
expect(tree).toMatchSnapshot()
})
我知道这是因为 Footer
组件使用了 react-router-dom
中的 Link
.为了解决这个问题,我在 BrowserRouter
中包裹了 Footer
组件:
I know this happens because Footer
component uses Link
from react-router-dom
. In order to solve this problem I wrapped Footer
component in BrowserRouter
:
const tree = renderer
.create(
<BrowserRouter>
<Footer />
</BrowserRouter>
)
.toJSON()
但现在它抛出错误:浏览器历史需要一个DOM
推荐答案
我用 MemoryRouter
而不是 BrowserRouter
解决了这个问题.
I used MemoryRouter
instead of BrowserRouter
and it solved the problem.
import React from 'react'
import { MemoryRouter } from 'react-router-dom'
import renderer from 'react-test-renderer'
import Footer from '../footer'
it('Footer renders correctly', () => {
const tree = renderer
.create(
<MemoryRouter>
<Footer />
</MemoryRouter>
)
.toJSON()
expect(tree).toMatchSnapshot()
})
这篇关于Jest 快照测试错误:您不应使用 <Link>在 <Router> 之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!