React测试库无法在测试之间重新呈现模态



我有一个模态组件,我正在渲染多个测试,像这样:

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();
});

Getting by testd失败。文档中呈现的唯一内容是一个空的

//Cancel test
<DocumentFragment>
<div />
<div>
...Modal elements
</div>
</DocumentFragment>
//Ok button
<DocumentFragment>
<div />
</DocumentFragment>

我尝试添加[cleanup][1],以及在afterEach中清除/重新初始化document,document.bodydocument.innerhtml,但都没有效果。当另一个测试被注释掉时,测试总是能成功运行。组件本身是用React钩子定义的,我没有看到模态组件产生任何全局副作用。是否有一种方法重置dom,以便在随后的测试中始终重新呈现模态?

我的情况是我错误地使用了行为和承诺。我遵循了Act的警告和提示,并像这样重构了Act:

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');
fireEvent.click(okButton);
await waitForElementToBeRemoved(screen.getByTestId('modal-client-id');
expect(modalComponent).not.toBeInDocument();
done();
});

因为我没有解决承诺和错误地调用done()渲染在我的测试中导致副作用。fireEvent也不需要外部换行,因为它已经在act中执行了动作。

最新更新