Robin Elvin
Robin Elvin

Reputation: 1255

React Router navigate away to new URL with tests

In my app I have react-router, redux and redux-first-history all working nicely. Certain routes in certain circumstances must navigate the user to another website e.g. for authentication with SAML. As React Router doesn't have a way to navigate to external sites I have to resort to manipulating the location.href.

An example route test would be:

  1. User lands on a login page (Route handled by RR6)
  2. User enters email address which is checked via an API
  3. Server responds that this user is set up for password login (4) or SAML (5)
  4. Password login - browser shows password box
  5. SAML login - browser navigates to SAML IdP (Handled by manipulating location)

When running tests I get errors from jsdom which is expected:

Error: Not implemented: navigation (except hash changes)

The problem is if I patch the location object in order to test as suggested by many then this breaks React Router navigation.

What is the best way to either handle external navigation or patch things correctly so that my tests work?

Upvotes: 0

Views: 1013

Answers (1)

mdmundo
mdmundo

Reputation: 2276

Just add another forward slash to the url.

import { useNavigate } from "react-router-dom";

let navigate = useNavigate();

navigate("//google.com");

Upvotes: 1

Related Questions