Testing Tanstack Router Components
Hello I'm using tanstack router and I'm trying write some tests using vitest for my components.
I have a component that has a useNavigate and I'd like to test that clicking a button, triggers a navigate() call with the correct to parameter.
My first challenge is getting the component to render at all, I have introduced act() , but it doesn't seem 100% reliable when used together with @testing-library/jest-dom/vitest , as running the test by itself it succeeds, but running the entire test suite it sometimes fails.
Is the below a good way to test components in vitest, that use various Tanstack Router hooks, or should I do it another way? I'm thinking about making below code generic in a render wrapper.
const rootRoute = new RootRoute({
component: () => <MyComponent />,
});
const router = new Router({
routeTree: rootRoute,
history: createMemoryHistory(),
});
await act(() => render(<RouterProvider router={router} />));
expect(screen.getByText('My Component Text')).toBeInTheDocument();2 Replies
unwilling-turquoiseOP•3y ago
the issue was that I was missing await in another tests in the same test file, but I'm still curious if this is the best approach!
ambitious-aqua•2y ago
I'm facing the issue of mocking those calls now, did you follow trough with this pattern?