【问题标题】:Jest mock document.activeElement开玩笑的模拟 document.activeElement
【发布时间】:2018-11-05 20:50:02
【问题描述】:

我有一个使用 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] 的属性 activeElement

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

【问题讨论】:

  • 错误信息有什么不清楚的地方?
  • 我如何测试该代码? return this.lastTabStop.focus();
  • 您可以尝试调用元素的焦点方法来使其成为活动元素。
  • @CBroe yh 我通过模拟 DOM 找到了解决方案。您可以查看我自己的答案以获取更多详细信息。

标签: javascript unit-testing dom jestjs


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 2020-03-05
    • 1970-01-01
    • 2020-10-20
    • 2021-05-22
    相关资源
    最近更新 更多