-1

当用户单击对话框上的“取消”按钮时,我正在尝试使用以下测试测试对话框的消失:

it("clicking on cancel hides the confirmation dialog", async() => {
    render(<ConfirmationDialog />);
    const cancelButton = screen.getByText("Cancel");
    fireEvent.click(cancelButton);
    await waitForElementToBeRemoved(() => screen.queryByText(/Cancel/i));
    expect(screen.queryByText(/Cancel/i)).toBeNull();
  });

但是上面的代码抛出了一个错误: TypeError: MutationObserver is not a constructor

  24 |     const cancelButton = screen.getByText("Cancel");
  25 |     fireEvent.click(cancelButton);
> 26 |     await waitForElementToBeRemoved(() => screen.queryByText(/Cancel/i));
     |           ^
  27 |     expect(screen.queryByText(/Cancel/i)).toBeNull();
  28 |   });
  29 | });

有人可以帮助我理解这个问题,因为我是测试库的新手。提前致谢。

4

2 回答 2

0

根据以下方法尝试:https ://github.com/testing-library/dom-testing-library/issues/477

npm install jest-environment-jsdom-sixteen

或者

yarn add -D jest-environment-jsdom-sixteen

然后通过 env cli param 设置它

 "scripts": {
        ...
       "test": "react-scripts test --env=jest-environment-jsdom-sixteen",
       ...
    }
于 2022-01-10T08:32:37.073 回答
0

You need to mock MutationObserver in your test :

import MutationObserver from '@sheerun/mutationobserver-shim';
window.MutationObserver = MutationObserver;

Your UI framework certainly depends on it.

There may be other way to mock MutationObserver, this is how I do it but it may not be the best way.

于 2022-01-10T08:24:20.763 回答