jsdom: Error: Not implemented: navigation

After recent upgrade jest (which uses jsdom in background) from version 21.2.0 to 22.0.6 I have started getting error: "Error: Not implemented:" navigation

My code relies on window.location and I use in tests:

beforeEach(() => {
                window.location.href = `/ms/submission/?mybib`;
                window.location.search = '?mybib';
});

Is there a way to define a value of window.location.search using new version of jsdom?

About this issue

  • Original URL
  • State: open
  • Created 6 years ago
  • Reactions: 90
  • Comments: 66 (6 by maintainers)

Commits related to this issue

Most upvoted comments

Allow me to post the answer to my own question 😁 I simply replace the usages of window.location = url; and window.location.href = url; with

window.location.assign(url);

and then in my tests I did:

sinon.stub(window.location, 'assign');
expect(window.location.assign).to.have.been.calledWith(url);

Works like a charm - hope it can be of help to someone else šŸ‘

If you don’t want to change your code to use location.assign - this seems to work with JSDom 11 and 13 (though there’s a chance JSDom might break it in the future…)

delete window.location;
window.location = {}; // or stub/spy etc.

I can see that there has been a lot of struggle with this from a lot of people.

In my case I had an issue while clicking on html anchor tag element in order to test that analytics are fired correctly. None of the above solutions worked.

In the end it was something very simple…

        clickedLink = getAllByRole('link').find((link) =>
          link.textContent?.includes(getDirectionsText),
        );

        clickedLink.addEventListener(
          'click',
          (event) => event.preventDefault(),
          false,
        );

        userEvent.click(clickedLink);

Attaching a click event listener to the anchor tag before emitting the click event does the trick.

I hope this will help someone else facing the same issue.

The last answer worked for me, but I had to define replace:

delete window.location
window.location = { replace: jest.fn() }

Hope it helps.

This is what worked for me:

    global.window = Object.create(window);
    const url = 'http://localhost';
    Object.defineProperty(window, 'location', {
      value: {
        href: url,
      },
      writable: true,
    });

jsdom does not support navigation, so setting window.location.href or similar will give this message. I’m not sure if Jest was just suppressing these messages before, or what.

This is probably something you should fix in your tests, because it means that if you were running those tests in the browser, the test runner would get completely blown away as you navigated the page to a new URL, and you would never see any tests results. In jsdom instead we just output a message to the console, which you can ignore if you want, or you can fix your tests to make them work better in more environments.

Anyway, I’d like to add more documentation on this for people, so I’ll leave this issue open to track doing so.

Is anyone else running into the same Error: Not implemented: navigation (except hash changes) during Jest tests that fire a click event on an anchor element with an href? For my tests, I’m spying on a function that gets called onClick and making assertions about that so I need to actually fire the click event on the anchor element.

The solutions above related to mocking window.location work for me where I am explicitly calling window.location.replace or window.location.assign, but don’t help for this case where the navigation originates from an anchor element being clicked.

Any ideas on solutions? Thanks!

Possible solution is to rely on dependency injection/mock for the window object in unit tests.

Something like:

it('can test', () => {
  const mockWindow = {location: {href: null}};
  fn({window: mockWindow});
  expect(mockWindow.href).toEqual('something');
});

This is not ideal but as said by @domenic:

This is probably something you should fix in your tests, because it means that if you were running those tests in the browser, the test runner would get completely blown away as you navigated the page to a new URL

For now we live with this and yes we change our implementation code for tests which is considered bad practice but we also sleep well at night!

Happy testing

We used pushState to make this to work

 window.history.pushState(
        {},
        '',
        'http://localhost/something/123?order=asc'
      );

@hontas’s solution helped:

I did use window.location.assign(Config.BASE_URL); in my code.

And here’s the test:

jest.spyOn(window.location, 'assign').mockImplementation( l => {
   expect(l).toEqual(Config.BASE_URL);
})

window.location.assign.mockClear();

@zxiest’s Jest version of @hontas’ solution didn’t work for me, but this did:

window.location.assign = jest.fn();
expect(window.location.assign).toHaveBeenCalledWith('https://correct-uri.com');
window.location.assign.mockRestore();

@hontas’s solution helped:

I did use window.location.assign(Config.BASE_URL); in my code.

And here’s the test:

jest.spyOn(window.location, 'assign').mockImplementation( l => {
   expect(l).toEqual(Config.BASE_URL);
})

window.location.assign.mockClear();

@Sabrinovsky No, I ended up just adding a script to the setupFiles in my jest config that would swallow the console errors coming from jsdom navigation so that they weren’t cluttering up our tests. More of a bandaid than anything else, but it sounded like these errors are to be expected in our test setup.

Here’s the script that I run before my tests:

// There should be a single listener which simply prints to the
// console. We will wrap that listener in our own listener.
const listeners = window._virtualConsole.listeners('jsdomError');
const originalListener = listeners && listeners[0];

window._virtualConsole.removeAllListeners('jsdomError');

// Add a new listener to swallow JSDOM errors that orginate from clicks on anchor tags.
window._virtualConsole.addListener('jsdomError', error => {
  if (
    error.type !== 'not implemented' &&
    error.message !== 'Not implemented: navigation (except hash changes)' &&
    originalListener
  ) {
    originalListener(error);
  }

  // swallow error
});

@nickhallph I replaced it to window.location as you wrote but result the same TypeError: Cannot redefine property: assign Any ideas?

Based on answer from @chrisbateman I managed to get this working in a Jest environment. For anyone who is using Jest, here is my workaround:

describe('', () => {
    const originalLocation = window.location;

    beforeEach(() => {
        delete window.location;

        window.location = {
            href: '',
        };
    });

    afterEach(() => {
        window.location = originalLocation;
    });

    it('', () => {
        // test here
    });
});

This is a difficult situation. JSDOM does not fully supports navigation (other than breadcrumbs) and JSDOM does not allow us to mock-out navigation. The end result is that I can’t write tests which ultimately attempt to trigger navigation.

If JSDOM did learn to navigate (I’m not even sure what that means), maybe I could assert about being on the appropriate page. For my testing use cases, though, asserting the navigation was triggered, rather than actually performed, is much cleaner/faster. It’s what I’ve historically done when testing using jsdom and now it’s broken.

If you get TypeError: Cannot assign to read only property 'assign' of object '[object Location]', then using something like this in your jest.setup.ts:

global.window = Object.create(window);
Object.defineProperty(window, 'location', {
  value: {
    ...window.location,
  },
  writable: true,
});

Same problem, I’m using window.location.search = foo; in my code and I would like to test it using jsdom (and jest) šŸ¤”

PS: Related to https://github.com/facebook/jest/issues/5266

Well in this case it wouldn’t doing anything different, other than not unloading the current page context. I’d still expect window.location.href to be updated, etc.

jsdom is not intended to provide a testing library. We’re providing a browser implementation. If it’s not suitable for your purposes, then you should not use it.

For anyone who is interested, here’s how I adapted the @markoboy solution in my Jest test with Vue3:

const button = wrapper.find('#some_id');
button.wrapperElement.addEventListener('click', (event) => event.preventDefault(), false);
button.trigger('click');

I am currently using Jest 26.0.1 and the below works for me:

  1. Use window.location.assign(url) to change the window location.

  2. Mock the location object as follows (note that not deleting and rebuilding the object first still results in the not implemented error in the noted version of Jest and earlier I think, also Object.defineProperty doesn’t work and still results in the error):

delete window.location;
window.location = {
    href: '',
    hostname: '',
    pathname: '',
    protocol: '',
    assign: jest.fn()
};
  1. Assert with:
expect(window.location.assign).toBeCalledWith(url);

It would be really nice if jest allowed us to easily mock location without all of these constant issues and changes. I was previously using just window.location.assign = jest.fn() without any problems for a long time, then I upgraded from v24 and now this.

Agree this should work out of the box. We mock window.location at FB, but that conflicts with jsdom’s History implementation.

Is there any way to find out which test is triggering the ā€œNot implemented: navigationā€ message? I have a suite of 43 tests - the error is being displayed only once and it keeps bouncing around. I can’t tell which test to fix!!! The stack trace gives me no indication of the culprit:

console.error
  Error: Not implemented: navigation (except hash changes)
      at module.exports (/Users/naresh/projects/mobx-state-router/node_modules/jsdom/lib/jsdom/browser/not-implemented.js:9:17)
      at navigateFetch (/Users/naresh/projects/mobx-state-router/node_modules/jsdom/lib/jsdom/living/window/navigation.js:76:3)
      at exports.navigate (/Users/naresh/projects/mobx-state-router/node_modules/jsdom/lib/jsdom/living/window/navigation.js:54:3)
      at Timeout._onTimeout (/Users/naresh/projects/mobx-state-router/node_modules/jsdom/lib/jsdom/living/nodes/HTMLHyperlinkElementUtils-impl.js:81:7)
      at listOnTimeout (internal/timers.js:531:17)
      at processTimers (internal/timers.js:475:7) undefined

    at VirtualConsole.<anonymous> (node_modules/jsdom/lib/jsdom/virtual-console.js:29:45)
    at module.exports (node_modules/jsdom/lib/jsdom/browser/not-implemented.js:12:26)
    at navigateFetch (node_modules/jsdom/lib/jsdom/living/window/navigation.js:76:3)
    at exports.navigate (node_modules/jsdom/lib/jsdom/living/window/navigation.js:54:3)
    at Timeout._onTimeout (node_modules/jsdom/lib/jsdom/living/nodes/HTMLHyperlinkElementUtils-impl.js:81:7)

As a small team, we would certainly appreciate help from the larger projects that depend on us to properly implement navigation in jsdom.

If anyone is interested, https://github.com/jsdom/jsdom/pull/1913 could be a good place to start.

Is there a way to fail tests when 'Error: Not implemented: navigation (except hash changes)' is thrown? I’m using vitest and couldn’t find any type of console message that would actually fail the tests (info, warning etc). I’m trying to do something like

const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
expect(spy).toHaveBeenCalledWith('Error: Not implemented: navigation (except hash changes)')

to make sure that the navigation is happening or not happening. In my case it’s important to make sure that the disabled link is not navigating anywhere on click

What’s the workaround here if the navigation event is coming from a deeply nested click on an element wrapped in an <a> tag? I’m not able to easily stub the onClick handler to add a e.preventDefault() and I didn’t see and easy way to intercept this error and know if it was an anchor click or location.assign

I’m getting this error too

Error: Not implemented: navigation (except hash changes)
    at module.exports (...\node_modules\jsdom\lib\jsdom\browser\not-implemented.js:9:17)
    at navigateFetch (...\node_modules\jsdom\lib\jsdom\living\window\navigation.js:74:3)

How would you test that code in a browser? Keep in mind that in the browser clicking on the link would blow away your whole page and throw away any test results. So whatever you would do to prevent that, will also prevent the much-less-dramatic warning message jsdom outputs to the console.

In all of your replies in this thread, you seem to be completely missing the fact that there are ways to test against the DOM and changes in the location, as is done when testing frameworks like React/Angular/Vue. We are able to fire events which manipulate the DOM, and this is pretty much what’s tested everywhere in these front-end frameworks. We aren’t testing inside of a browser; we’re testing using jest or other test frameworks; we just need to be able to actually stub out these for things like React to be rid of the console.error that is produced by JSDom.

Perhaps you could help users here with some direction on doing this, rather than telling everybody to go fix their ā€œbroken codeā€ that wasn’t even written by them. Nothing you’ve said here has been helpful or even really factual at all.

Kinda blows my mind that this issue is still open without conclusion since Jan of 2018.

Frankly, this issue is about the console.error coming out of JSDom, and it’s not about any sort of broken tests. The error just looks like it’s something breaking, but it’s just a console.error.

@Sabrinovsky No, I ended up just adding a script to the setupFiles in my jest config that would swallow the console errors coming from jsdom navigation so that they weren’t cluttering up our tests. More of a bandaid than anything else, but it sounded like these errors are to be expected in our test setup.

Here’s the script that I run before my tests:

// There should be a single listener which simply prints to the
// console. We will wrap that listener in our own listener.
const listeners = window._virtualConsole.listeners('jsdomError');
const originalListener = listeners && listeners[0];

window._virtualConsole.removeAllListeners('jsdomError');

// Add a new listener to swallow JSDOM errors that orginate from clicks on anchor tags.
window._virtualConsole.addListener('jsdomError', error => {
  if (
    error.type !== 'not implemented' &&
    error.message !== 'Not implemented: navigation (except hash changes)' &&
    originalListener
  ) {
    originalListener(error);
  }

  // swallow error
});

Thank you for this!

For anyone who wants to make TypeScript happy

import { VirtualConsole } from 'jsdom';

declare global {
  interface Window {
    _virtualConsole: VirtualConsole;
  }
}

This worked for me

delete window.location
window.location = { assign: jest.fn() }

The issue with examples is that methods and getters are not use. What I do is basically replace Location object by URL object. URL has all the properties of Location (search, host, hash, etc).

const realLocation = window.location;

describe('My test', () => {

    afterEach(() => {
        window.location = realLocation;
    });

    test('My test func', () => {

        // @ts-ignore
        delete window.location;

        // @ts-ignore
        window.location = new URL('http://google.com');

        // ...
    });
});

@chrisbateman @hamzahamidi thanks, that solutions worked well.

Maybe it’s not a good practice, but we have some tests, those rely on location/host/hostname and other location properties. So mocking location as we want and restoring afterwards worked for me.

const realLocation = window.location;

describe('bla bla', () => {
  afterEach(() => {
    window.location = realLocation;
  });

  it('test where I want to use hostname', () => {
    delete window.location;
    window.location = { 
      hostname: 'my-url-i-expect.com'
    };
    // check my function that uses hostname
  });
});

Totally get what you’re saying. The recent Jest 22 update went from JSDOM 9 to 11 IIRC, so the behavior back in 9.x might have been quite different.

All that aside, I would love to see navigation implemented in JSDOM with some sort of flag to make it a no-op in terms of loading a different page (in similar spirit to HTML5 pushstate.) The library is very commonly used for testing purposes so, while perhaps a quirky request, it would be used often.

In my situation project upgraded Jest from 23 to 26 version. I had a problem with location.search. Had the same error Error: Not implemented: navigation. Module I tested gets values of search query params. Next implementation worked for me:

beforeAll(() => {
  delete window.location;
  window.location = new URL('your URL');
})

afterAll(() => {
  window.location.search = '';
})

@hontas’s solution helped:

I did use window.location.assign(Config.BASE_URL); in my code.

And here’s the test:

jest.spyOn(window.location, 'assign').mockImplementation( l => {
   expect(l).toEqual(Config.BASE_URL);
})

window.location.assign.mockClear();

This worked for me, thanks! However I had to use the done argument from jest test(), otherwise I wouldn’t be sure that the expect was evaluated and the test might had ended successfully anyway:

it('should', (done) => {
jest.spyOn(window.location, 'assign').mockImplementation( l => {
   expect(l).toEqual(Config.BASE_URL);
   done();
})

window.location.assign.mockClear();
}

@hontas’s solution helped:

I did use window.location.assign(Config.BASE_URL); in my code.

And here’s the test:

jest.spyOn(window.location, 'assign').mockImplementation( l => {
   expect(l).toEqual(Config.BASE_URL);
})

window.location.assign.mockClear();

Thanks mate, you’ve saved me a day! 😃

Same problem as @yuri-sakharov running mocha.

By no means I seem able to replace/update/mock or do anything with window.location.*. The only way I see around this is creating my own custom window.location mock and change the entire codebase to depend on that.

It seems that in some cases you just can’t get rid of this error. 😦

If you click on HyperlinkElement, you get to the HTMLHyperlinkElementUtilsImpl class, which at some point gets right into the navigateFetch function, which does nothing but throw an error

function navigateFetch(window) {
  // TODO:
  notImplemented("navigation (except hash changes)", window);
}

So if you use a HyperlinkElement in a test, you are doomed to this error.

There could be two solutions:

  1. Override link href to prevent it from navigation in test
link.setAttribute('href', '');
  1. For the helpless cases, I wrote a function to avoid noisy console error messages while not missing other cases:
const realError = console.error;

const disableConsoleError = () => {
    console.error = jest.fn();
};

const restoreConsoleError = () => {
    console.error = realError;
};

export const consoleErrorWrapper = (callback: () => void) => {
    disableConsoleError();
    callback();
    restoreConsoleError();
};

and I use it as act method from react:

it('should track click', async () => {
       consoleErrorWrapper(async () => {
            const trackClick = jest.spyOn(require('TrackingUtil'), 'trackClick');

            render(<Product product={productMock} />);
            const link = screen.getByTestId('product-link');

            await userEvent.click(link);

            expect(trackProducts).toHaveBeenCalled();
        });
 });

If it helps anyone this is what I did. We are using mocha not jest so only have sinon available.

exports.jsdom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost' });
const { window } = exports.jsdom;

/* This enables stubbing window.location.assign for url changes */
const { location } = window;
delete window.location;
window.location = { ...location, assign: () => {} };

You can then freely stub… const assignStub = sandbox.stub(window.location, 'assign');

This worked for me.

delete global.window.location
global.window.location = { href: 'https://test.com' }

@hontas Does not work for me 😦 Unable to rewrite assign/replace property

As I understand jest changed something in new version (ā€œjestā€: ā€œ^26.0.1ā€) so this works right now:

// Mock
  Object.defineProperty(window, 'location', {
    value: {
      pathname: '/terminals',
      assign: jest.fn(),
    },
  });

// Then test
expect(window.location.assign).toBeCalledWith('/auth');

After updating to jsdom 12.2.0 got error: TypeError: Cannot redefine property: assign on const assign = sinon.stub(document.location, 'assign') how to fix it?