【问题标题】:Jest - Testing modals in React gives error开玩笑 - 在 React 中测试模态会出错
【发布时间】:2019-10-09 00:16:38
【问题描述】:

我正在使用 react-test-renderer 和 Jest 来测试反应组件。但是如果我像这样测试一个 react-mui 模态对话框:

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

但是,然后我得到一个错误:

错误:失败:“错误:未捕获'警告:无效容器已 被提供。这可能表明正在使用另一个渲染器 除了测试渲染器。 (例如,ReactDOM.createPortal 在 ReactTestRenderer 树内。)不支持。%s'

我应该如何测试然后响应门户以使该测试正常工作?

【问题讨论】:

标签: reactjs jestjs react-test-renderer


【解决方案1】:

试着把它放在你的测试中:

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

【讨论】:

  • 这段代码是如何工作的?我们需要放它的原因是什么?
  • @MaryamSaeidi 我认为您应该添加 import ReactDOM from 'react-dom 并在导入下方添加 beforeAll 代码。
  • 我试过这个,但得到了Cannot set property 'scrollTop' of null
【解决方案2】:

基于 Oliver 的回答,但针对 TypeScript 用户:

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

  afterAll(() => {
    ReactDOM.createPortal = oldCreatePortal;
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    • 2021-06-16
    • 2021-01-09
    • 1970-01-01
    • 2020-03-17
    • 1970-01-01
    • 2018-12-27
    相关资源
    最近更新 更多