问题
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()
})
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()
but now it throws error: Browser history needs a DOM
回答1:
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()
})
来源:https://stackoverflow.com/questions/55791828/jest-snapshot-testing-error-you-should-not-use-link-outside-a-router