Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest - Testing modals in React gives error

I am using react-test-renderer with Jest to test react components. But if I test a react-mui modal dialog like this:

describe('Dashboard', function () {
  let dashboard;
  beforeEach(async () => {
    testRenderer = TestRenderer.create(<MemoryRouter><Route component={Dashboard} /></MemoryRouter>);
    dashboard = testRenderer.root.findByType(Dashboard);
    await waitForExpect(() => expect(dashboard.instance.state.hasLoaded).toBeTruthy());
  });


  it('opens dialog on clicking the new class', async () => {
    const button = testRenderer.root.findByType(Button);
    expect(dashboard.instance.state.showDialog).toBeFalsy();
    button.props.onClick();
    expect(dashboard.instance.state.showDialog).toBeTruthy();
  });
});

But, then I get an error:

Error: Failed: "Error: Uncaught 'Warning: An invalid container has been provided. This may indicate that another renderer is being used in addition to the test renderer. (For example, ReactDOM.createPortal inside of a ReactTestRenderer tree.) This is not supported.%s'

How should I test then react portals to make this test work?

like image 382
Leff Avatar asked May 22 '19 13:05

Leff


2 Answers

Try putting this in your tests:

beforeAll(() => {
    ReactDOM.createPortal = jest.fn((element, node) => {
        return element
    })
});
like image 113
Oliver Watkins Avatar answered Oct 26 '22 06:10

Oliver Watkins


Based on Oliver's answer, but for TypeScript users:

describe("Tests", () => {
  const oldCreatePortal = ReactDOM.createPortal;
  beforeAll(() => {
    ReactDOM.createPortal = (node: ReactNode): ReactPortal =>
      node as ReactPortal;
  });

  afterAll(() => {
    ReactDOM.createPortal = oldCreatePortal;
  });
});
like image 3
Andre Miras Avatar answered Oct 26 '22 08:10

Andre Miras