How test routing with links in Next JS?

Viewed 2499

I'm beginner in NextJS environment and I'm migrating an application from common ReactJS. That's a simple test of a link to another page. So, how I should refactor my test?

*I'm using Jest and Testing Library.

// My current code in ReactJS
test('Should go to Post page', () => {
        const post = mockPostModel()
        const history = createMemoryHistory({ initialEntries: ['/'] })
        render(
            <Router history={history}>
                <BlogPost post={post} />
            </Router>
        )
        fireEvent.click(screen.getByTestId('link'))
        expect(history.location.pathname).toBe(`/post/${post.title}`)
    })
1 Answers

To be able to render your Next.js page using jsdom you can use next-page-tester. It's a quite new library, so not a lot of documentation and not everything is supported, but there is an example of usage on the README.

Another option would be to use end-to-end tests instead of jsdom. It's a slower option but everything will be correctly rendered.

Related