【问题标题】:Jest, React Testing Library Async Await error开玩笑,反应测试库异步等待错误
【发布时间】:2023-02-09 19:25:19
【问题描述】:
React Js 代码是
const AwaitAsync = () => {
const [data, setData] = useState("");
const handleClick = () => {
setTimeout(() => {
setData("Data after 4 secons")
}, 1000);
}
return (
<div>
<h2>Await Async</h2>
<h4>Data will come after 4 secons</h4>
<p>
<button onClick={handleClick}>Click to display data</button>
</p>
{
data && <p data-testid="abc">{data}</p>
}
</div>
)
}
单元测试用例是但单元测试用例失败
错误是:let dat = await screen.findByTestId("abc");
describe('Async Await', () => {
it("Async Await Test", async () => {
// jest.setTimeout(10000);
render(<AwaitAsync />);
const btn = screen.getByRole('button');
fireEvent.click(btn);
let dat = await screen.findByTestId("abc");
expect(dat).toHaveTextContent("Data after 4 secons")
});
})
单元测试用例失败
【问题讨论】:
标签:
reactjs
unit-testing
react-hooks
react-testing-library
【解决方案1】:
你应该Enable Fake Timers
这将替换 setTimeout() 和其他计时器功能的原始实现。
另见testing-recipes#timers
import { fireEvent, render, screen, act } from '@testing-library/react';
import '@testing-library/jest-dom';
import React from 'react';
import { AwaitAsync } from '.';
describe('Async Await', () => {
it('Async Await Test', async () => {
jest.useFakeTimers();
render(<AwaitAsync />);
const btn = screen.getByRole('button');
fireEvent.click(btn);
act(() => {
jest.advanceTimersByTime(1000);
});
expect(screen.getByTestId('abc')).toHaveTextContent('Data after 4 secons');
});
});
测试结果:
PASS stackoverflow/75395180/index.test.tsx (8.706 s)
Async Await
✓ Async Await Test (76 ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.tsx | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.22 s