jsdom icon indicating copy to clipboard operation
jsdom copied to clipboard

Error: Not implemented: navigation

Open ramusus opened this issue 8 years ago • 69 comments

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 avatar Jan 12 '18 20:01 ramusus

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)

cpenarrieta avatar Jan 17 '18 01:01 cpenarrieta

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.

domenic avatar Jan 22 '18 00:01 domenic

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.

quantizor avatar Jan 25 '18 06:01 quantizor

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!

domenic avatar Jan 25 '18 07:01 domenic

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.

quantizor avatar Jan 25 '18 07:01 quantizor

@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 avatar Jan 29 '18 09:01 hontas

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 👍

hontas avatar Jan 29 '18 09:01 hontas

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

xixixao avatar Mar 05 '18 09:03 xixixao

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.

Zirro avatar Mar 05 '18 10:03 Zirro

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

vvo avatar Apr 25 '18 09:04 vvo

@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 avatar Sep 18 '18 19:09 zxiest

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

yvele avatar Sep 27 '18 15:09 yvele

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?

yuri-sakharov avatar Oct 22 '18 11:10 yuri-sakharov

@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

nickhallph avatar Oct 22 '18 19:10 nickhallph

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.

yordis avatar Oct 22 '18 21:10 yordis

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

yuri-sakharov avatar Oct 24 '18 01:10 yuri-sakharov

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.

nielskrijger avatar Nov 01 '18 15:11 nielskrijger

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

tomturton avatar Nov 08 '18 15:11 tomturton

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.

chrisbateman avatar Nov 26 '18 20:11 chrisbateman

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

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

Hope it helps.

ggregoire avatar Jan 21 '19 19:01 ggregoire

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?

RichardWright avatar Feb 07 '19 18:02 RichardWright

This is what worked for me:

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

sergioviniciuss avatar Feb 14 '19 17:02 sergioviniciuss

We used pushState to make this to work

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

yordis avatar Feb 14 '19 17:02 yordis

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.

mpareja avatar Feb 22 '19 11:02 mpareja

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

That if you have control to the target url, but what if you are loading google or Instagram website. or any website? how can you solve this problem ?

beshoo avatar May 06 '19 01:05 beshoo

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

scriptex avatar May 13 '19 05:05 scriptex

I solved this issue using this config. I wanted to test redirection for hash urls:


    beforeEach(() => {
      delete global.window;
      global.window = {
        location: { replace: jest.fn(url => ({ href: url })) },
      };
    });
    it('should redirect hash url', () => {
      window.location.hash = '#/contrat?id=8171675304';
      global.window.location.href =
        'http://localhost:3000/#/contrat?id=8171675304';
      redirectHashUrl();

      expect(window.location.replace).toHaveBeenCalled();
    });

hamzahamidi avatar May 24 '19 09:05 hamzahamidi

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

aibolik avatar Jun 12 '19 09:06 aibolik

This is what worked for me:

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

it doesnot work on a CI like circleci

elemanhillary-zz avatar Aug 26 '19 09:08 elemanhillary-zz

@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! :)

vafanasenka avatar Oct 11 '19 09:10 vafanasenka