我有一個 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 毫秒之前。任何幫助表示贊賞謝謝
uj5u.com熱心網友回復:
您可以等待稍短并檢查文本不在檔案中:
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原因,但如果真的延遲了,我建議考慮使用假計時器:
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()
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/355613.html
標籤:javascript 反应 测试 玩笑
