gpt4 book ai didi

javascript - 如何使用 Jest 测试 url 更改

转载 作者:行者123 更新时间:2023-12-02 13:37:23 35 4
gpt4 key购买 nike

我有以下功能要测试

function tradePage() {
setTimeout(function() {
window.location.pathname = document
.getElementById('button')
.getAttribute('new-page');
}, 100);
}

我编写了以下测试:

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');
});

但是当我运行测试时,我收到此错误:

    expect(received).toEqual
Expected value to equal:
"/new-url"
Received:
"blank"

我已经做过/尝试过的事情

  • 我的packages.json 已经设置了“testURL”

  • 我找到了这个可能的解决方案(但不起作用):

     Object.defineProperty(window.location, 'pathname', {
    writable: true,
    value: '/page/myExample/test',
    });

还有什么想法我还可以尝试吗?

最佳答案

我通过在测试开始时声明全局变量找到了一种工作方法:

global.window = { location: { pathname: null } };

并像这样检查这个变量:

expect(global.window.location.pathname).toContain('/new-url');

效果很好。

关于javascript - 如何使用 Jest 测试 url 更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50977862/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com