In a recent project, I needed to write a test for a React component which performed a redirect. Something like this:

jsdom (version bundled with Jest 24.9.0) does not like this code and spits an error: Not implemented: navigation (except hash changes), making the test fail.

Previously (back in 2018, I think), it was possible to fix this with a code like this:

Alas, for jsdom >= 14 this no longer works. One of the solutions was to redefine window object completely, and then use Object.defineProperty() to redefine location object. However, instead of redefining window it is possible to redefine just location:

The complete solution with Jest may look like this (TypeScript):

Jest: How to Mock window.location.href
Tagged on:                 

Leave a Reply

Your email address will not be published. Required fields are marked *