[英]Jest mock document.activeElement
我有一个使用DOM的函数
const trap = {
// ...
init() {
if (document.activeElement === this.firstTabStop) {
return this.lastTabStop.focus();
}
}
}
module.exports = trap.init;
我尝试模拟document.activeElement
但会引发错误。
global.document.activeElement = mockFirstTabStop;
mockFirstTabStop
只是函数模拟,但是无论我放在哪里,错误都是一样的。
TypeError:无法设置只有吸气剂的[object Object]的属性activeElement
因此,我如何测试该条件以期望this.lastTabStop.focus()
被调用?
解决方案是创建一个模拟的DOM并将其用作方案:
trap.js
const trap = {
// ...
init() {
if (document.activeElement === this.firstTabStop) {
return this.lastTabStop.focus();
}
}
}
module.exports = trap.init;
trap.test.js
const trap = require('./trap.js');
// Mock a DOM to play around
document.body.innerHTML = `
<div>
<button id="btn1">btn 1 </button>
<button id="btn2">btn 2 </button>
<button id="btn3">btn 3 </button>
</div>
`;
// Mock Jest function
const mockBtnFocus = jest.fn();
const mockBtnFirst = document.getElementById('btn1');
const mockBtnLast = document.getElementById('btn3');
it('should focus this.lastTabStop when activeElement is this.firstTabStop', () => {
mockBtnFirst.focus(); // <<< this is what sets document.activeElement
mockBtnLast.focus = mockBtnFocus;
// Mock trap context to access `this`
trap.bind({
firstTabStop: mockBtnFirst,
lastTabStop: mockBtnLast,
});
expect(mockBtnLast.focus).toHaveBeenCalledTimes(1);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.