Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
541 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).toEqual('/new-url');

That worked fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...