【问题标题】:React testing-library unable to re render modal in between tests反应测试库无法在测试之间重新呈现模态
【发布时间】: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],以及清除/重新初始化documentdocument.bodydocument.innerhtml,但均无效。当另一个注释掉时,测试总是成功运行。它自己的组件是用 React 钩子定义的,我没有看到模态组件产生任何全局副作用。有没有办法重置 dom 以在后续测试中始终重新呈现模态?

【问题讨论】:

    标签: reactjs jestjs react-testing-library testing-library


    【解决方案1】:

    我的情况是我错误地使用了行为和承诺。我跟着Act warnings and tips 重构了这个行为:

       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 中执行了操作。

    【讨论】:

      猜你喜欢
      • 2021-06-23
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-13
      • 1970-01-01
      • 2018-10-04
      • 2020-01-21
      相关资源
      最近更新 更多