I have the React/Typescript component below. It works as expected, but I'm trying to prove that with a test (using testing-library). I want to ensure that it correctly receives the level
parameter and renders it to the page:
import React from "react";
import { useParams } from "react-router-dom";
type QuestionGridParams = {
level: string;
};
export const QuestionGrid = () => {
const { level } = useParams<QuestionGridParams>();
return (
<>
<header>
<h1>Level {level}</h1>
</header>
</>
);
};
I'd expected to do this by stubbing the context, or the function that returns the context, so that it always returns a specified value for the parameter. None of my searching has given a solution that I can get to work. Closest I have come is the test below, which only proves that the component works if no parameter is passed in. I want to pass in a level
of 4, for example, and assert that there is an element with the text Level 4
.
I don't think that this is the approach I need, it just happens to be the only way for now I can get the test not to error when useParams()
is invoked..
test("page renders in the absence of a 'level' parameter", () => {
const layout = render(
<Router history={createMemoryHistory()}>
<QuestionGrid/>
</Router>
);
const header: any = layout.getByText("Level");
expect(header).toBeInTheDocument();
});
Any help getting past this mindblock would be greatly appreciated.