0

I have a function which runs on page-load and reads the URL, setting the data to an object.

To test this I need to set the location at the start of the test.

If I try using window.location.assign, window.location.replace or window.location.href I get this error:

Error: Not implemented: navigation (except hash changes)

I've tried all of the answers in this post, but none of them works.


If I try to reassign window.location.assign:

test('Correct load-state', () => {
  window.location.assign = jest.fn()
  window.location.assign('/about')
})

I get:

TypeError: Cannot assign to read only property 'assign' of object '[object Location]'

If I try Object.defineProperty:

test('Correct load-state', () => {
  const mockResponse = jest.fn()
  Object.defineProperty(window, 'location', {
    value: {
      href: window.location.href,
      assign: mockResponse
    },
    writable: true
  })
  window.location.assign('/about')

  console.log(mockResponse.mock) // assign *is* called with '/about'
  console.log(href) // http://localhost/
})

assign is called but nothing updates to match /about.


Is there any way around this?

Daniel_Knights
  • 7,940
  • 4
  • 21
  • 49

0 Answers0