javascript - 开 Jest 模拟 document.activeElement

标签 javascript unit-testing dom jestjs

我有一个使用 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/

相关文章:

javascript - 选择所有复选框 JS 切换问题

unit-testing - 如何对存储库方法进行单元测试

javascript - 向动态创建的元素添加 id

javascript - 修改存储在变量中的innerHTML不起作用

java - 我的 Junit 测试不工作

javascript - 幕后发生了什么,这是正确的方法吗? (通过 Javascript 修改 DOM)

javascript - 从Python中的 session 存储中获取变量

javascript - 如何复制指针事件 :none in JavaScript 的行为

javascript - 检测正在移动的 DOM 中元素的位置

oop - 如何对非公共(public)逻辑进行​​单元测试