Jest + React: Reset location.href before each test

597 Views Asked by At

I've got a React component that takes into account URL params and then makes some fetches taking into account that param. By default, if no param is set, it uses a default value.

The issue is that Jest seems not to reset the href property after each test, so if the previous test navigates to my-url?some=param, the next test will have still that href set.

This means that after changing that href from interacting with the component in the tests, the next test will have the previous value. A side effect from this is that I cannot test the default value if the param is not set, because it will be always set by the previous test.

What I've tried

  beforeEach(() => {
    window.location.assign('');
  });

Throws error Not implemented: navigation (except hash changes).

  beforeEach(() => {
    window.location.href = '';
  });

Throws error Not implemented: navigation (except hash changes).

  beforeEach(() => {
    Object.defineProperty(window, 'location', {
      value: {
        href: ''
      }
    });
  });

Throws error Cannot redefine property 'location'.

In all of these cases, it does not matter if it's an empty string '' or a correct URL like http://localhost.

The question

Is there some way to reset the href property before each test? I don't mean to mock it: it should work as it's default behaviour, but just reset it before each test.

Shouldn't that be the default behavior for Jest? What's the use in cleaning up the DOM automatically but leaving the href with the value from previous test?

2

There are 2 best solutions below

3
Marek Rozmus On

It looks like these are not implemented in JSDOM.

You need to mock it anyway. You can try sth like this:

const mockHref = jest.fn();
Object.defineProperty(window, 'location', {
  value: {
    get href() {
      return mockHref();
    },
  },
});

describe('it should work', () => {
  beforeEach(() => {
    mockHref.mockReturnValue('empty');
  })

  it('should work', () => {
    expect(window.location.href).toEqual('empty')
  })
})
0
Anubhav Vishwakarma On

Yes you should add

beforeEach(() => {
  Object.defineProperty(window, 'location', {
      writable: true,
      value: {
        href: ${yourUrl},
      },
   });
});

The writable:true should make it possible to reset the url back to yourUrl before every test case.