I have the following function to test
function tradePage() {
  setTimeout(function() {
    window.location.pathname = document
      .getElementById('button')
      .getAttribute('new-page');
  }, 100);
}
And I've written the following test:
test('should change page when button is clicked', () => {
  var button = document.querySelector('#button');
  jest.useFakeTimers();
  button.dispatchEvent(createEvent('click'));
  jest.runAllTimers();
  expect(window.location.pathname).toEqual('/new-url');
});
But when I run the test I get this error:
    expect(received).toEqual
    Expected value to equal:
    "/new-url"
    Received:
    "blank"
Things I've already done/tried
My packages.json already have the "testURL" set up.
I found this possible solution (that didn't work):
 Object.defineProperty(window.location, 'pathname', {
   writable: true,
   value: '/page/myExample/test',
 });
Any ideas what else I can try?
instead of having to set the pathname to null, you can just check it like
expect(global.window.location.href).toContain('/new-url'). 
so that way you don't have to assign null to the pathname.
I found a working method by declaring in the beginning of the test a global variable:
global.window = { location: { pathname: null } };
and checked this variable like this:
expect(global.window.location.pathname).toContain('/new-url');
That worked fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With