Jest - Testing modals in React gives error

旧街凉风 提交于 2020-12-12 05:27:16

问题


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?


回答1:


Try putting this in your tests:

beforeAll(() => {
    ReactDOM.createPortal = jest.fn((element, node) => {
        return element
    })
});


来源:https://stackoverflow.com/questions/56257998/jest-testing-modals-in-react-gives-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!