Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error: Not implemented: navigation #2112

Open
ramusus opened this issue Jan 12, 2018 · 66 comments
Open

Error: Not implemented: navigation #2112

ramusus opened this issue Jan 12, 2018 · 66 comments

Comments

@ramusus
Copy link

ramusus commented Jan 12, 2018

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?

@ramusus ramusus changed the title "Error: Not implemented:" navigation Error: Not implemented: navigation Jan 12, 2018
@cpenarrieta
Copy link

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)

@domenic
Copy link
Member

domenic commented Jan 22, 2018

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.

@quantizor
Copy link

quantizor commented Jan 25, 2018

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.

@domenic
Copy link
Member

domenic commented Jan 25, 2018

I don't think we should add a flag that makes your tests run different in jsdom than in browsers. Then your stuff could be broken in browsers (e.g. it could be redirecting users to some other page, instead of doing the action that your tests see happening) and you wouldn't even notice!

@quantizor
Copy link

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.

@hontas
Copy link

hontas commented Jan 29, 2018

@domenic I'm having the same issue and I was wondering if there is some sort of best practice to setup JSDOM with an app that sets window.location. From what I can tell JSDOM throws an error when trying to set window.location and logs an error when trying to set window.location.href - however I'm reading on mdn that the two should be synonyms. Should I be updating the location in another way thats easier to stub?
Thankful for help 😅

@hontas
Copy link

hontas commented Jan 29, 2018

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 👍

@xixixao
Copy link

xixixao commented Mar 5, 2018

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

@Zirro
Copy link
Member

Zirro commented Mar 5, 2018

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, #1913 could be a good place to start.

@vvo
Copy link

vvo commented Apr 25, 2018

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

@zxiest
Copy link

zxiest commented Sep 18, 2018

@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();

@yvele
Copy link

yvele commented Sep 27, 2018

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 jestjs/jest#5266

@yuri-sakharov
Copy link

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?

@nickhallph
Copy link

nickhallph commented Oct 22, 2018

@yuri-sakharov

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?

sinon.stub(document.location, 'assign')

needs to be:

sinon.stub(window.location, 'assign')

you need to replacedocument with window

@yordis
Copy link

yordis commented Oct 22, 2018

I have the following function

export const isLocalHost = () => Boolean(
  window.location.hostname === 'localhost' ||
  // [::1] is the IPv6 localhost address.
  window.location.hostname === '[::1]' ||
  // 127.0.0.1/8 is considered localhost for IPv4.
  window.location.hostname.match(
    /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
  )
);

for me to be able to test that it works I inject directly the hostname

it('#isLocalHost should return true for all the cases of localhost', () => {
    window.location.hostname = 'localhost';
    expect(isLocalHost()).toBeTruthy();

    window.location.hostname = '[::1]';
    expect(isLocalHost()).toBeTruthy();

    window.location.hostname = '127.0.0.1';
    expect(isLocalHost()).toBeTruthy();

    // Reset back the hostname to avoid issues with it
    window.location.hostname = '';
  });

But I am getting this error.

I don't expect jsdom to fully implement the navigation but at least add the keys and mock the functions.

I am confused on why I keep getting this error, I just want to be able to setup the value.

@yuri-sakharov
Copy link

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

@nielskrijger
Copy link

nielskrijger commented Nov 1, 2018

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.

@tomturton
Copy link

@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();

@chrisbateman
Copy link

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.

@ggregoire
Copy link

ggregoire commented Jan 21, 2019

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

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

Hope it helps.

@RichardWright
Copy link

I'm getting TypeError: Cannot redefine property: assign with sinon 7.2.3 and jsdom 13.2.0. No idea why this works for some people and not others?

@sergioviniciuss
Copy link

sergioviniciuss commented Feb 14, 2019

This is what worked for me:

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

@yordis
Copy link

yordis commented Feb 14, 2019

We used pushState to make this to work

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

@mpareja
Copy link

mpareja commented Feb 22, 2019

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.

@s-taylor
Copy link

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');

@blephy
Copy link

blephy commented Jun 3, 2021

@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
});

This worked for me with angular.
All stub workaround provided in other messages doesn't work with angular.

Ty @Sabrinovsky

@s-taylor
Copy link

s-taylor commented Jun 8, 2021

Second attempt at this, my previous attempt broke using the history lib, presumably because assign was no longer a getter.

This solves that issue...

// This makes window.location.assign writable so sinon can stub
function patchLocation(location) {
  const clone = Object.create(Object.getPrototypeOf(location));
  const descriptors = Object.getOwnPropertyDescriptors(location);
  descriptors.assign.writable = true;
  descriptors.assign.configurable = true;
  Object.defineProperties(clone, descriptors);
  return clone;
}

const { location } = window;
delete window.location;
window.location = patchLocation(location);

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

@fooey
Copy link

fooey commented Jun 10, 2021

@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;
  }
}

@Whoaa512
Copy link

Whoaa512 commented Jul 9, 2021

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

MonkeyDo added a commit to metabrainz/listenbrainz-server that referenced this issue Sep 13, 2021
Solves warnings about navigation not being implemented in JSDOM:
jsdom/jsdom#2112
@markoboy
Copy link

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.

@dnalbach
Copy link

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');

@jhnance
Copy link

jhnance commented Nov 6, 2022

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!

@mattcphillips

I think this is the issue I just ran into. The response below yours is what triggered a realization for me. I was testing this in the browser by setting a breakpoint on the beforeunload event. So, I just added the same thing in my test and got it to work. Still get the annoying console logs but the test is passing.

However, I will say that I'm a bit confused why the test passes on its own without this kind of event listener, but needs the event listener when run in the same file as other tests. Probably something else I'm missing here that could make my test better...

Anyway, here's what I tried. Again, this is for an anchor element with an onClick:

window.addEventListener('beforeunload', function () {
  // make your assertion here based on w/e it is your anchor's click handler does
});

// click your anchor after later in your test

@kevr
Copy link

kevr commented Jan 9, 2023

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.

@domenic
Copy link
Member

domenic commented Jan 9, 2023

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.

@kevr
Copy link

kevr commented Jan 10, 2023

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.

Makes much more sense.

@Focus-me34
Copy link

Hey guys!

I found a solution without using mock or Object.defineProperty or by creating a. new window etc. ...
Here it is :

  afterEach(() => {
      window.history.replaceState({}, "", decodeURIComponent(http://localhost/));
  });

I think the reason for the error we all had is that there's something wrong going on with the browser history in test env (I'm personally using react-router v6 with ).

Anyway, the code snippet above replaces the current URL with the one passed as the third argument of the .replaceState() function by manipulating not the URL directly, but the history of navigation.

More about this function here: https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState

Hope it was helpful! 🔥

@AnnaYuS
Copy link

AnnaYuS commented Mar 17, 2023

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

@Andre-the-Viking
Copy link

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

  it("show a error message if the download fails", async () => {
....
    const spyConsoleError = jest
      .spyOn(console, "error")
      .mockImplementation(() => {});

....
    await waitFor(() => {
      expect(spyConsoleError).toHaveBeenCalledWith(
        expect.stringContaining(expectedConsoleError),
        undefined
      );
    });

.... // other expects...
    expect(messageError).toHaveBeenCalledWith({ message: expectedError });

@IuliiaBondarieva
Copy link

IuliiaBondarieva commented Jun 7, 2023

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();
        });
 });

@nilslindemann
Copy link

nilslindemann commented Jun 10, 2023

I out comment ...

window._virtualConsole.emit("jsdomError", error);

... in node_modules/jsdom/lib/jsdom/browser/not-implemented.js. This silences jsdom and the message will not be printed.

@janeklb
Copy link

janeklb commented Aug 28, 2023

Yet-Another-Solution (TypeScript friendly). Only works if you have control over the window.location.* calls you want to test.

IMO this is actually best as it explicitly removes side-effect code from your business logic. If you want, you can then

  1. create a windowLocation module/file etc.
// adjust WindowLocation to accommodate all the window.location functionality you need

type WindowLocation = Pick<Location, 'reload' | 'assign' | 'pathname' | 'href' | 'origin'>;

export const windowLocation: WindowLocation = {
  reload: () => window.location.reload(),
  assign: (url) => window.location.assign(url),
  get pathname() {
    return window.location.pathname;
  },
  get href() {
    return window.location.href;
  },
  get origin() {
    return window.location.origin;
  },
};
  1. replace all window.location.* calls with windowLocation.*
    eg.

    windowLocation.reload(); // instead of window.location.reload();
  2. set up your test framework to mock access to this module
    eg. if you're using jest, update your jest.setup.ts / setupFilesAfterEnv file:

    type WindowLocationModule = typeof import('./path/to/windowLocation');
    jest.mock<>('./path/to/windowLocation', () => ({
      windowLocation: {
        assign: jest.fn(),
        href: 'https://fake.url/',
        origin: 'https://fake.url',
        pathname: '/',
        reload: jest.fn(),
      },
    }));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests