使用 jest 25.x 测试聚焦元素

Esz*_*ter 6 javascript focus reactjs jestjs enzyme

我们使用带有expect(document.activeElement).toBe(myElement)模式的玩笑测试来确定元素在交互后是否正确聚焦。升级到 jest 25 (jsdom 15) 后,所有此类测试都失败了,document.activeElement似乎总是null.

例如,以下测试适用于 Jest 24.x 但不适用于 25.x

// example.spec.js
import * as React from 'react';

it('should find active element', () => {
    const wrapper = mount(<input />);
    const inputNode = wrapper.find('input').getDOMNode();
    inputNode.focus();
    expect(document.activeElement).toBe(inputNode); // fails with 'expected' being null
});
Run Code Online (Sandbox Code Playgroud)

使用 Jest 25.x 测试元素是否聚焦的最佳方法是什么?