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

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...