I am testing a navbar component that uses React Router. I am trying to use createMemoryHistory from the history package to test browser navigation.
I am using react-router-dom v 6.3.0 and history v 5.3.0
My test looks like this:
import { render, screen } from "@testing-library/react";
import React from "react";
import { Router } from "react-router-dom";
import { createMemoryHistory } from "history";
import { NavBarComponent } from "../navBarComponent";
import userEvent from "@testing-library/user-event";
describe("<NavBarComponent/>", () => {
beforeEach(() => {
const history = createMemoryHistory({ initialEntries: ["/"] });
render(
<Router location={history.location} navigator={history}>
<NavBarComponent></NavBarComponent>
</Router>
);
});
describe("Clicking on buttons to change route", () => {
it("navigates to correct paths", () => {
expect(history.location.pathname).toBe("/"); // <----- IDE error is here: Property 'location' does not exist on type 'History'
userEvent.click(screen.getByText("Collection"));
expect(history.location.pathname).toBe("/collection");
});
});
});
Running the test gives the following error:
TypeError: Cannot read properties of undefined (reading 'pathname')
36 | // </Router>
37 | // );
> 38 | expect(history.location.pathname).toBe("/");
However, when I break out the beforeEach code into each individual test, the test works fine:
import { render, screen } from "@testing-library/react";
import React from "react";
import { Router } from "react-router-dom";
import { createMemoryHistory } from "history";
import { NavBarComponent } from "../navBarComponent";
import userEvent from "@testing-library/user-event";
describe("<NavBarComponent/>", () => {
describe("Clicking on buttons to change route", () => {
it("navigates to correct paths", () => {
const history = createMemoryHistory({ initialEntries: ["/"] });
render(
<Router location={history.location} navigator={history}>
<NavBarComponent></NavBarComponent>
</Router>
);
expect(history.location.pathname).toBe("/");
userEvent.click(screen.getByText("Collection"));
expect(history.location.pathname).toBe("/collection");
});
});
});
My IDE indicates that the type of history when it is defined in the test itself is MemoryHistory, and that is also the type when it is defined in beforeEach.
However, accessing the history object inside of a test when it was defined in beforeEach indicates that the type is History, not MemoryHistory.
What's going on here? Why does the type seem to change when the object is defined in beforeEach as opposed to inside the test itself?