我想为我的Footer
组件编写快照测试,但是会引发错误:You should not use <Link> outside a <Router>
。这是我的代码:
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
组件使用了Link
中的react-router-dom
。为了解决此问题,我将Footer
组件包装在BrowserRouter
中:
const tree = renderer
.create(
<BrowserRouter>
<Footer />
</BrowserRouter>
)
.toJSON()
但现在它会引发错误:Browser history needs a DOM
答案 0 :(得分:0)
我用MemoryRouter
代替了BrowserRouter
,它解决了问题。
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()
})