Skip to content

RouterProvider not working in tests (Vitest) #12512

@rothsandro

Description

@rothsandro

I'm using React Router as a...

library

Reproduction

  1. Clone the repo https://github.com/rothsandro/repro.react-router-provider-vitest
  2. Install dependencies npm install
  3. Run the tests npm run test

There is a simple test that renders the RouterProvider with a memory router.
We then click on a button that triggers a navigation with flushSync: true using the useNavigate() hook.

System Info

System:
    OS: macOS 14.2.1
    CPU: (10) arm64 Apple M1 Max
    Memory: 35.43 GB / 64.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.17.0 - ~/.nvm/versions/node/v20.17.0/bin/node
    npm: 10.8.2 - ~/.nvm/versions/node/v20.17.0/bin/npm
    pnpm: 9.12.3 - /opt/homebrew/bin/pnpm
    bun: 1.0.36 - ~/.bun/bin/bun
  Browsers:
    Brave Browser: 131.1.73.97
    Chrome: 130.0.6723.70
    Safari: 17.2.1
  npmPackages:
    react-router: ^7.0.2 => 7.0.2 
    vite: ^5.4.11 => 5.4.11

Used Package Manager

npm

Expected Behavior

The test should run successfully and without error or warning.

Actual Behavior

The tests throws an error:

useNavigate() may be used only in the context of a <Router> component.

The upgrade guide mentions that for non-DOM the router provider should be imported from react-router instead of react-router/dom. The repro uses Vitest with happy-dom so it's a DOM environment. There is a 2nd test that uses the router provider from react-router. This solves the error from above but will log a warning to the console that the router provider from react-router/dom should be used for flushSync (skip the failing test to see the warning).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions