Jest 模拟 document.activeElement

san*_*a-p 2 javascript dom unit-testing jestjs

我有一个使用 DOM 的函数

const trap = {
  // ...
  init() {
    if (document.activeElement === this.firstTabStop) {
      return this.lastTabStop.focus();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

module.exports = trap.init;

我尝试模拟document.activeElement但它抛出了一个错误。

global.document.activeElement = mockFirstTabStop;
Run Code Online (Sandbox Code Playgroud)

mockFirstTabStop 只是功能模拟,但无论我放在哪里,错误都是一样的。

类型错误:无法设置只有 getter 的 [object Object] 的属性 activeElement

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

san*_*a-p 5

解决方案是创建一个模拟 DOM 并将其用作场景:

陷阱.js

const trap = {
  // ...
  init() {
    if (document.activeElement === this.firstTabStop) {
      return this.lastTabStop.focus();
    }
  }
}

module.exports = trap.init;
Run Code Online (Sandbox Code Playgroud)

陷阱.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);
});
Run Code Online (Sandbox Code Playgroud)