在聚焦节点时,jsdom 9.1+不会设置document.activeElement

时间:2016-07-31 07:38:20

标签: unit-testing reactjs mocha jsdom enzyme

我正在使用带有酶+ mocha + chai的jsdom来测试React组件的行为。该组件有一个方法来聚焦DOM节点(使用通常的node.focus()),我想测试节点在被调用时实际上是聚焦的。

要知道哪个节点是关注的,我将document.activeElement与我期望关注的节点进行比较。

但是,在升级到jsdom 9.1+之后,即使在调用节点的document.activeElement方法之后,HTMLBodyElement似乎总是focus()

使用jsdom 9.0,测试运行正常。

我阅读了与焦点事件相关的jsdom 9.1 + contains some changes,但我无法理解make document.activeElement如何按预期行事。有什么帮助吗?

3 个答案:

答案 0 :(得分:3)

您是否在想要关注的元素上缺少tabindex属性?必须将其设置为jsdom的有效整数才能将其解释为可聚焦。

您可以在jsdom source code

中看到这一点

答案 1 :(得分:2)

扩展@Epeli 的回答:

要聚焦的元素确实必须添加到 DOM 树中,然后才能将 document.activeElement 设置为它。

如果您正在安装一个组件并想检查该组件内部是否有焦点,请尝试在测试中添加以下内容:

test(() => {
    const wrapper = mount(<SomeComponent />)
    document.body.appendChild(wrapper.find('#FocusElement').getDOMNode())
    // the rest of your test...
})

答案 2 :(得分:0)

它可能不起作用的一个原因是该元素尚未添加到DOM树中。

    "use_strict";
    function getPlane(){
        let url = "https://test.api.amadeus.com/v2/shopping/flight-offers?originLocationCode=SYD&destinationLocationCode=BKK&departureDate=2021-02-01&returnDate=2021-02-05&adults=1&max=3";
        fetch(url,{
            method:"GET",
            headers:{
            "Authorization": "Bearer ACCESS_TOKEN_HERE",
            },
            mode:"cors",
            catch:"default"
        }).then(function(response){
            if(response.ok){
                return response.json();
            }else{
                throw new Error(error);
            }
        }).then(function(data){
            console.log(data);
            //query data here
            document.getElementById("flight").insertAdjacentHTML('afterbegin',data.data[0].itineraries[0].segments[0].operating.carrierCode)
        }).catch(function(error){
            console.log(error);
        });
    }

    getPlane();