-1

I am trying to test disappearance of dialog box when user clicks "cancel" button on my dialog box using the following test:

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

But the above code throws an error : 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 | });

Can someone help me understanding this issue as I am new to testing library. Thanks in advance.

Anshul
  • 7,914
  • 12
  • 42
  • 65

2 Answers2

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.

Florian Motteau
  • 3,467
  • 1
  • 22
  • 42
0

Try this according to: https://github.com/testing-library/dom-testing-library/issues/477

npm install jest-environment-jsdom-sixteen

or

yarn add -D jest-environment-jsdom-sixteen

and then set it via env cli param

 "scripts": {
        ...
       "test": "react-scripts test --env=jest-environment-jsdom-sixteen",
       ...
    }
true_gler
  • 544
  • 6
  • 23