我正在使用React 测试库对我的 ReactJS 代码进行单元测试。UI 中有几个异步事件,例如获取数据和单击按钮时显示新页面。React 代码有点像这样:
// Inside ParentComponent.tsx
const [isChildVisible, setChildVisibility] = useState(false);
const showChild = () => setChildVisibility(true);
return(
<>
<button data-testid="show-child" onClick={showChild}>Show Child</button>
{isChildVisible && <ChildComponent {..childProps}/>}
</>
)
Run Code Online (Sandbox Code Playgroud)
在ChildComponent安装时,它会获取一些数据,然后使用水合数据重新渲染自身。我的单元测试如下所示:
jest.mock('../../../src/service'); // mock the fetch functions used by ChildComponent to fetch its data
describe('ParentComponent', () => {
test('renders ChildComponent on button click', async () => {
const screen = render(<ParentComponent />);
userEvent.click(screen.getByTestId('show-child'));
await (waitFor(() => screen.getByText('text rendered by child')));
});
});
Run Code Online (Sandbox Code Playgroud)
当我运行此测试时,出现错误"TestingLibraryElementError: …