useLoaderData must be used in a data router – Vitest – npm run test

In attempting to test React components that implement the React Router API, I’m getting an error while running tests at the same time. If either test is commented out the error is not raised and the other test passes.

  • Error: useLoaderData must be used within a data router.
afterEach(cleanup);

test(
    `Verify that <Timestamp /> displays both the UNIX and UTC dates for a date provided in milliseconds`, () => {

        vi.mock("react-router-dom", async () => {
            const module = await vi.importActual("react-router-dom");
            return {
                ...module,
                useLoaderData: vi.fn(() => {
                    return {unix: 7728271946, utc: "Tue, 31 Mar 1970 10:44:31 GMT"}
                })
            }
        })
        
        render(
            <MemoryRouter initialEntries={['/']}>
                <Timestamp />
            </MemoryRouter>
        );
        const timestamps = screen.getAllByRole("paragraph");
        expect(timestamps[0]).toHaveTextContent("Date in UNIX: 7728271946");
        expect(timestamps[1]).toHaveTextContent("Date in UTC: Tue, 31 Mar 1970 10:44:31 GMT");
    }
);
test(
    "Verify that DateError a displays a message that the supplied date is an invalid date", () => {
        vi.mock("react-router-dom", async() => {
            const module = await vi.importActual("react-router-dom");
            return {
                ...module,
                useRouteError: vi.fn(() => "282347223489234 is an invalid date!")
            }
        });
        render(
            <MemoryRouter initialEntries={["282347223489234"]}>
                <DateError />
            </MemoryRouter>
        );
        const message = screen.getByRole("paragraph");
        expect(message).toHaveTextContent("282347223489234 is an invalid date!")
    }
);
function Timestamp(props) {
    const date = useLoaderData();

    return <div className="timestamp_wrapper">
        <p className="timestamp">Date in UNIX: {date.unix}</p>
        <p className="timestamp">Date in UTC: {date.utc}</p>
    </div>
}

function DateError(props) {
    const error = useRouteError()

    return <div className="timestamp_wrapper">
        <p className="timestamp_error">{error}</p>
    </div>
}

main.jsx

const router = createBrowserRouter(
    createRoutesFromElements(
        <Route path="/" element={null}>
            <Route path=":date" element={<Timestamp />} errorElement={<DateError />} loader={get_timestamps}/>
        </Route>
    )
);

ReactDOM.createRoot(document.getElementById('root')).render(
    <RouterProvider router={router} />
)

I’m not sure if this error is a result of how my tests are written with Vitest or React Router given I’m still learning how to use both.