【发布时间】:2021-09-27 07:18:39
【问题描述】:
我有一个模态组件,我正在为多个测试渲染,如下所示:
const result = render(<MyModal {...myTestProps} />);
const modalComponent = screen.getByTestId('modal-client-id');
在我的一项测试中,我忽略了模式:
it("Closes modal when cancel button is clicked", async(done) => {
const result = render(<MyModal {...myTestProps} />);
const modalComponent = screen.getByTestId('modal-client-id');
const cancelButton = screen.getByTestId('modal-cancel-button');
await act(async () => {
new Promise((resolve, reject) => {
fireEvent.click(cancelButton);
done();
});
});
expect(modalComponent).not.toBeInDocument();
});
但在随后的测试中:
it("Closes modal when successful", async(done) => {
const result = render(<MyModal {...myTestProps} />);
const modalComponent = screen.getByTestId('modal-client-id');
const okButton = screen.getByTestId('modal-ok-button');
await act(async () => {
new Promise((resolve, reject) => {
fireEvent.click(okButton);
done();
});
});
expect(modalComponent).not.toBeInDocument();
});
通过 testId 获取失败。文档中唯一呈现的是一个空
//Cancel test
<DocumentFragment>
<div />
<div>
...Modal elements
</div>
</DocumentFragment>
//Ok button
<DocumentFragment>
<div />
</DocumentFragment>
我尝试在afterEach 中添加[cleanup][1],以及清除/重新初始化document、document.body 和document.innerhtml,但均无效。当另一个注释掉时,测试总是成功运行。它自己的组件是用 React 钩子定义的,我没有看到模态组件产生任何全局副作用。有没有办法重置 dom 以在后续测试中始终重新呈现模态?
【问题讨论】:
标签: reactjs jestjs react-testing-library testing-library