Jest testing: implementation of MemoryRouter #735
Unanswered
NicoleHoerner
asked this question in
Web
Replies: 1 comment
-
Darn, my bad Nicole. I suggested you use MemoryRouter for testing your links, but that's nonsensical. Blame it on me, my thinking was off here. import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Router } from 'next/router';
import Navigation from "./Navigation";
Router.router = {
push: jest.fn(),
prefetch: jest.fn(), // You can mock other functions as needed
};
test("navigation links work", () => {
render(<Navigation />);
const dashboardLink = screen.getByText("Dashboard");
const flightsLink = screen.getByText("Flights");
const aboutLink = screen.getByText("About");
userEvent.click(dashboardLink);
expect(Router.router.push).toHaveBeenCalledWith("/");
userEvent.click(flightsLink);
expect(Router.router.push).toHaveBeenCalledWith("/flight_list");
userEvent.click(aboutLink);
expect(Router.router.push).toHaveBeenCalledWith("/about");
}); See if this works. If not, let me know. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello,
I am working on a test with jest which I need to improve as the expect function is missing. Goal is to check if the navigation links work. Here it is:
This one works fine but I got the reminder that this test is missing the expect function. Without it, the test is not meaningful.
So the suggestion I received was to implement an expect function and MemoryRouter in order to check if a click on a given link actually works by inspecting the page that gets displayed afterward.
For your reference: navigation component
What have I already done:
install react-router-dom
wrap my component with MemoryRouter: (I tried it with async function and without) Example:
Description of the error/problem:
The error that I get:
TestingLibraryElementError: Unable to find an element with the text: Flight Information.
or something like that:
TestingLibraryElementError: Unable to find an accessible element with the role "heading" and name "Flight Information"
I also tried Route and Routes
In the end I got to this test:
This works BUT: this test verifies that the links are set up correctly, it doesn't guarantee that the entire navigation flow within my application is working perfectly. It only checks the correctness of the href attributes.
Thanks for helping!
Regards, Nicole
Beta Was this translation helpful? Give feedback.
All reactions