Jest snapshot testing error: You should not use <Link> outside a <Router>

谁都会走 提交于 2021-01-28 12:13:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!