Kis*_*iss 6 javascript unit-testing jestjs
我有以下功能要测试
function tradePage() {
setTimeout(function() {
window.location.pathname = document
.getElementById('button')
.getAttribute('new-page');
}, 100);
}
Run Code Online (Sandbox Code Playgroud)
而且我编写了以下测试:
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');
});
Run Code Online (Sandbox Code Playgroud)
但是,当我运行测试时,出现以下错误:
expect(received).toEqual
Expected value to equal:
"/new-url"
Received:
"blank"
Run Code Online (Sandbox Code Playgroud)
我已经完成/尝试过的事情
"testURL"设置好了。我发现了这个可能的解决方案(不起作用):
Object.defineProperty(window.location, 'pathname', {
writable: true,
value: '/page/myExample/test',
});
Run Code Online (Sandbox Code Playgroud)还有什么我可以尝试的想法吗?
小智 6
而不必将路径名设置为 null,您可以像这样检查它
expect(global.window.location.href).toContain('/new-url').
这样您就不必将 null 分配给路径名。
通过在测试开始时声明一个全局变量,我找到了一种有效的方法:
global.window = { location: { pathname: null } };
Run Code Online (Sandbox Code Playgroud)
并像这样检查此变量:
expect(global.window.location.pathname).toEqual('/new-url');
Run Code Online (Sandbox Code Playgroud)
很好。