3

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 Answer 1

7

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()
})

Sign up to request clarification or add additional context in comments.

1 Comment

If anyone is still having issues due to keys not matching in the snapshot. You can follow this example and add initialEntries={[ { pathname: '/', key: 'testKey' } ]} or keyLength={0} in the MemoryRouter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.