To test the Nextjs Link component with Jest and Testing-Library, you can follow these steps:
Install the necessary dependencies: Jest, Testing-Library, and the @testing-library/react
and @testing-library/jest-dom
add-ons.
Import the components you want to test: Link
from next/link
, and any other components that the Link component uses.
Set up your test environment: create a mock function and invoke it with the appropriate arguments. This will simulate a user clicking on the Link component.
Write your test case: use Testing-Library methods like render
and fireEvent
to simulate user interactions and check the expected outcomes.
Here's an example test case for the Nextjs Link component:
import React from 'react'
import { render, fireEvent } from '@testing-library/react'
import { Link } from 'next/link'
describe('Link', () => {
test('renders correctly', () => {
const { getByText } = render(
<Link href="/">
<a>Home</a>
</Link>
)
const linkElement = getByText('Home')
expect(linkElement).toBeInTheDocument()
})
test('navigates to the correct page on click', () => {
const push = jest.fn()
const { getByText } = render(
<Link href="/" passHref>
<a onClick={(e) => {
e.preventDefault()
push('/')
}}>Home</a>
</Link>
)
const linkElement = getByText('Home')
fireEvent.click(linkElement)
expect(push).toHaveBeenCalledTimes(1)
expect(push).toHaveBeenCalledWith('/')
})
})
In the first test case, we're simply rendering the Link component and checking that it's displaying the correct text ("Home").
In the second test case, we're testing that the Link component correctly navigates the user to the home page when clicked. Here, we're using a mock function (push
) to simulate the page navigation, since we can't actually navigate to a different page during a test. We're using the fireEvent.click
method to simulate a user clicking on the Link component, and checking that the push
function is called with the correct arguments.
Asked: 2023-07-14 10:38:52 +0000
Seen: 7 times
Last updated: Jul 14 '23