【问题标题】:setFocus in useEffect cause errors in testssetFocus in useEffect 导致测试出错
【发布时间】:2022-01-15 17:10:14
【问题描述】:

我已经为我的 React 组件编写了几个测试,当我排除以下代码时它们都可以工作:

useEffect(() => {
    if (lastClickedElement) {
        const findElement = document.getElementById(lastClickedElement);
        findElement.focus();
    } else {
        const findFirstLink = document.querySelectorAll("a");
        findFirstLink[0].focus();
    }

但是,当我包含它时,我收到错误:“无法读取未定义的属性'焦点'”。 谁能解释为什么我的测试在没有它的情况下可以工作,然后在包含它时导致此错误?

我尝试使用 if 语句,如果 findFirstLink 等于“null”则不返回任何内容,但随后我收到此错误“Uncaught TypeError: Cannot read property 'focus' of null throwed”。

代码如下所示:

{data.items.map((item, i) => {
      return (
           <div>
                <a href={item.id}>{item.label}</a>
           </div>
             )
         }
)}

【问题讨论】:

  • 可能是半相关的问题,为什么使用document.getElementById 而不是将ref 传递给相关元素并使用ref.current.focus()

标签: reactjs react-hooks karma-runner enzyme


【解决方案1】:

因为 jest 没有在无头浏览器中运行,所以没有document 可以这么说。

快速修复的最佳解决方案是模拟您的 getElementByID 和 querySelectorAll 以返回一个包含 focus: jest.fn() 对象的数组

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 2017-02-18
    相关资源
    最近更新 更多