gpt4 book ai didi

javascript - 开 Jest 模拟 document.activeElement

转载 作者:行者123 更新时间:2023-11-28 17:39:54 24 4
gpt4 key购买 nike

我有一个使用 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: Cannot set property activeElement of [object Object] which has only a getter

那么,如何测试该条件以期望调用 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);
});

关于javascript - 开 Jest 模拟 document.activeElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48166739/

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