This project serves as a showcase and template for testing React Router v7 applications using TWD (Testing While Developing).
It demonstrates how to effectively test route components, loaders, and actions in isolation using React Router's createRoutesStub.
- 🧪 TWD Integration: Full setup with TWD for end-to-end style testing of components.
- 🛣️ Route Testing: Examples of testing routes in isolation using
createRoutesStub. - 🔄 Mocking: Patterns for mocking loaders and actions.
- 🧩 Reusable Utils: Utility functions to streamline the testing setup.
-
Install dependencies:
npm install
-
Start the development server:
npm run dev
To run the TWD tests:
npx twdOr if you have a specific script set up in package.json.
The core philosophy of testing in this project is to avoid spinning up the entire application for every test. Instead, we use createRoutesStub from react-router to create a lightweight router instance that renders only the component under test.
- Test Harness (
app/routes/testing-page.tsx): We use a dedicated route (/testing) as a blank canvas for mounting our test components. This file is required for the tests to run, as it initializes TWD and provides the DOM element where tests are mounted. - Route Stubs: We define stubs for our routes, allowing us to inject mock data into loaders and spy on actions.
- TWD Interaction: We use TWD to interact with the rendered DOM, just like a user would.
- Create a
.twd.test.tsxfile inapp/twd-tests/. - Import the setup utility:
import { setupReactRoot } from "./utils";
- Setup the root in
beforeEach:let root: ReturnType<typeof createRoot> | undefined; beforeEach(async () => { root = await setupReactRoot(); });
- Write your test using
createRoutesStub:it("should render my page", async () => { const Stub = createRoutesStub([ { path: "/", Component: MyPage, loader() { return { someData: "mocked" }; }, }, ]); root!.render(<Stub />); // Use TWD to assert await twd.should(screenDom.getByText("mocked"), "be.visible"); });
app/routes/: Your application routes.app/twd-tests/: TWD test files.utils.ts: Contains thesetupReactRoothelper.helloWorld.twd.test.tsx: Basic example.todoList.twd.test.tsx: Advanced example with loaders and actions.
app/routes/testing-page.tsx: The empty harness page used for mounting tests.
To add this setup to your own React Router project:
- Install TWD: Follow the official documentation.
- Create the Harness Route: Add a route (e.g.,
app/routes/testing-page.tsx) that renders a simple container with adata-testid. - Add the Utils: Copy
app/twd-tests/utils.tsto your project. This handles the mounting/unmounting logic. - Start Testing: Create your test files and start writing tests!