I am attempting to do a simple test on a simple navigation app using React Testing Library. I am currently attempting to use the example method shown in RTL's own guide, however that doesn't seem to be working.
App.js
return (
<BrowserRouter>
<div>
<Route exact path="/" component={Home} />
<Route exact path="/hello" component={Hello} />
</div>
</BrowserRouter>
);
Home.jsx
return (
<div data-testid="home-container">
<Link to="/hello">Link to hello</Link>
</div>
);
Hello.jsx
return (
<div data-testid="hello-container">
<Link to="/">< Back</Link>
<h1 data-testid="hello-title">Hello component</h1>
</div>
);
Test for Home.jsx in Home.spec.js
test("Navigate to hello page when clicked", async () => {
const history = createMemoryHistory();
render(
<Router history={history}>
<Home />
</Router>
);
// check pre-nav page
expect(screen.getByText(/Link to hello/i)).toBeInTheDocument();
const leftClick = { button: 0 };
userEvent.click(screen.getByText(/Link to hello/i), leftClick);
// check we have navigated to the correct path - THIS PASSES!
expect(history.location.pathname).toBe("/hello");
// check that the content changed to the new page - THIS FAILS!
expect(screen.getByText(/Hello component/i)).toBeInTheDocument();
});
Error...
The error I seem to be getting is that it can't find the /Hello component/ text, still thinking that it's on the Home component... Which is weird because the history location check clearly shows it being on the Hello path.
Unable to find an element with the text: /Hello component/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
Ignored nodes: comments, <script />, <style />
<body>
<div>
<div
data-testid="home-container"
>
<a
href="/hello"
>
Link to hello
</a>
</div>
</div>
</body>