【问题标题】:Jest testing JavaScript code element does not appear before setTimeout finishes在 setTimeout 完成之前不出现 Jest 测试 JavaScript 代码元素
【发布时间】:2021-12-20 08:53:12
【问题描述】:

我有一个 React 组件 ComponentA,一旦渲染,启动 setTimeout 函数延迟 500 毫秒,然后渲染正文。我需要测试一下,在这 500 毫秒内,正文没有出现,我不知道是怎么回事。

组件A:

function ComponentA() {
  const [showIndicator, setShowIndicator] = useState(false);

  useEffect(()=> {
   setTimeout(()=> setShowIndicator(true), 500);
  }) 

  return (showIndicator && <h1>Hello</h1>);
}

到目前为止,我目前的测试设置是

import {render} from '@testing-library/react'

describe("Test Component A", () => {
  test("it should not show text during first 500 ms", async () => {
     // Point A: rendering time
      const {container, getByText} = render(<ComponentA  />)
     // Point B: before delay
     // Need to assert text is not shown yet before delay
      await sleep(500);
     // Poin C: now text should appear
      expect(getByText('Hello')).toBeInTheDocument()
  });
});

它正在传递,但我不知道如何断言文本在 500 毫秒过去之前不出现,以及如何知道断言发生的那一刻是在 500 毫秒之前。感谢您的帮助,谢谢

【问题讨论】:

    标签: javascript reactjs testing jestjs


    【解决方案1】:

    您可以稍等片刻并检查文本不在文档中:

    test("it should not show text during first 500 ms", async () => {
      const {container, getByText} = render(<ComponentA  />)
      await sleep(499);
      expect(getByText('Hello')).not.toBeInTheDocument()
    });
    

    我也不确定sleep 的来源,但如果它真正延迟我建议考虑fake timers

    test("it should not show text during first 500 ms", async () => {
      const {container, getByText} = render(<ComponentA  />)
      jest.advanceTimersByTime(499);
      expect(getByText('Hello')).not.toBeInTheDocument()
    });
    

    最后你可以将 2 个测试用例合并在一起(不是因为我认为测试用例的数量很重要,而是因为你实际上测试了与延迟显示相关的相同方面):

    test("shows text after 500 ms delay", async () => {
      const {container, getByText} = render(<ComponentA  />)
      jest.advanceTimersByTime(499);
      expect(getByText('Hello')).not.toBeInTheDocument()
      jest.advanceTimersByTime(2);
      expect(getByText('Hello')).toBeInTheDocument()
    });
    

    【讨论】:

      猜你喜欢
      • 2019-06-26
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 2015-03-25
      • 2023-03-06
      相关资源
      最近更新 更多