Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test url change with Jest

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?

like image 705
Kiss Avatar asked Jun 21 '18 21:06

Kiss


2 Answers

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.

like image 36
Ibrahimj Avatar answered Nov 14 '22 21:11

Ibrahimj


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.

like image 98
Kiss Avatar answered Nov 14 '22 23:11

Kiss