javascript - 如何使用 Jest 测试 url 更改
问题描述
我有以下功能要测试
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).toEqual('/new-url');
那工作得很好。
推荐阅读
- node.js - 处理多个 POST 请求
- angular - Angular FormGroup 不包含模型属性
- android - Android MVVM:当相同数据是来自不同服务器端点的响应的一部分时,如何从另一个存储库更新存储库中的数据?
- angular - 如何在Angular 8中使用条件templateUrl动态创建组件?
- excel - 对象“_Worksheet”的错误 1004 方法“保护”失败
- botframework - 在 LUIS 和 QnA Maker 中直接支持俄语和阿拉伯语
- reactjs - 如何使用 getfiledecoder 在 ant design 中验证 url
- roku - 使用 Brightscript 为 ROKU 应用程序解析 JSON
- python - 在非常大的数据帧上提高迭代的性能
- android - Android 离线地图 - OSMDroid