Jest模拟document.activeElement

3

我有一个使用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:无法设置仅具有getter的 [object Object] 的活动元素属性

那么,我该如何测试条件来期望调用 this.lastTabStop.focus()


错误信息有什么不清楚的地方? - undefined
如何测试这个条件?return this.lastTabStop.focus(); - undefined
1
你可以尝试调用元素的focus方法,使其成为活动元素。 - undefined
@CBroe 嗯,我通过模拟 DOM 找到了解决方案。你可以查看我的答案以获取更多详细信息。 - undefined
2个回答

5
解决方案是创建一个模拟的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);
});

2

另一种解决方案:

const element = document.createElement('div');

Object.defineProperty(document, 'activeElement', { value: element, writable: false });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接