Reactjs React test-如何在使用渲染道具渲染的jsx中测试函数

Reactjs React test-如何在使用渲染道具渲染的jsx中测试函数,reactjs,unit-testing,react-test-renderer,Reactjs,Unit Testing,React Test Renderer,我想测试使用render prop渲染的jsx的内容。我使用反应测试渲染器进行测试 这是菜单组件,它有一个我想测试的渲染道具: <Menu menuItems={createMenuItems(cities, onOpenCity)} render={(openMenu, onClick, children) => ( <> <Button buttonRef={node =&

我想测试使用render prop渲染的jsx的内容。我使用反应测试渲染器进行测试

这是
菜单
组件,它有一个我想测试的渲染道具:

   <Menu
      menuItems={createMenuItems(cities, onOpenCity)}
      render={(openMenu, onClick, children) => (
        <>
          <Button
            buttonRef={node => this.anchorEl = node}
            onClick={onClick}
            className={`${classes.iconWrapper} ${classes.marginIcons} ${openMenu && classes.active}`}
            <Book fill={openMenu ? '#000' : '#fff'}/>
          </Button>
          {children(this.anchorEl)}
        </>
      )}
    >
    </Menu>
SimpleTestContext是一个类,它具有一些用于设置测试的帮助器方法:

class SimpleTestContext {
  defaultNodeMock = {
    createNodeMock: (element) => {
      if (element.type === 'input') {
        // return document.createElement('input');
        //console.log('createNodeMock got input', element.props);
      }
      if (element.type === 'textarea') {
        // console.log('createNodeMock got textarea', element.props);
        return document.createElement('textarea');
      }
      return null;
    }
  };

  testRenderer = {unmount: () => {}}; // null object

  setup() {
    this.consoleErrorSpy = jest.spyOn(global.console, 'error');
    this.consoleErrorSpy.mockReset();
    Document.prototype.exitFullscreen = jest.fn();
    jest.useFakeTimers();
  }

  tearDown() {
    this.testRenderer.unmount();
    jest.runAllTimers();
    jest.useRealTimers();
    expect(this.consoleErrorSpy).not.toHaveBeenCalled();
  }

  act(func)  {
    TestRenderer.act(func);
  }

  render(jsx, options) {
    this.testRenderer = TestRenderer.create(jsx, options);
    return this.testRenderer;
  }

  renderWithDefaultNodeMock(jsx) {
    return this.render(jsx, this.defaultNodeMock);
  }

  async waitForComponent(component) {
    await waitForExpect(() => expect(
      this.testRenderer.root.findAllByType(component)
        .map(instance => ({ props: instance.props, type: instance.type }))).toHaveLength(1));
    return this.testRenderer.root.findByType(component);
  }

  async waitForComponentByProps(props) {
    await waitForExpect(() => expect(
      this.testRenderer.root.findAllByProps(props)
        .map(instance => ({props: instance.props, type: instance.type}))).toHaveLength(1));
    return this.testRenderer.root.findByProps(props);
  }

  async waitForComponentToLoad(component) {
    const instance = await this.waitForComponent(component);
    await waitForExpect(() => expect(instance.instance.state.hasLoaded).toBeTruthy());
    return instance;
  }

  setupBeforeAfter() {
    beforeEach(() => {
      this.setup();
    });
    afterEach(() => {
      this.tearDown();
    });
  }
}
我的问题是,如果我在尝试查找MenuList的地方运行测试,例如:

  it('renders menu', () => {
    const menu = renderMenu();
    console.log(menu.instance);
    const menuList = menu.findByType(MenuList);
    console.log(menuList);
  });
我得到一个错误:

错误:未找到节点类型为“未定义”的实例


如何测试使用render prop渲染jsx的组件渲染的内容?

在您的测试文件中,MenuList似乎是
未定义的
,请检查您是否正确导入了它我已检查并正确导入了它错误消息很奇怪(在IMO中已损坏),但看起来似乎应该失败<如果code>findByType没有准确地找到类型为
MenuList
的一个元素,并且您在测试中没有提供一个元素,那么它将抛出。测试中的
renderFunction
只返回
按钮
元素是否可以为
菜单列表添加代码?
export function setupTeardownWithTestRenderer() {
  const context = new SimpleTestContext();
  context.setupBeforeAfter();
  return context;
}
class SimpleTestContext {
  defaultNodeMock = {
    createNodeMock: (element) => {
      if (element.type === 'input') {
        // return document.createElement('input');
        //console.log('createNodeMock got input', element.props);
      }
      if (element.type === 'textarea') {
        // console.log('createNodeMock got textarea', element.props);
        return document.createElement('textarea');
      }
      return null;
    }
  };

  testRenderer = {unmount: () => {}}; // null object

  setup() {
    this.consoleErrorSpy = jest.spyOn(global.console, 'error');
    this.consoleErrorSpy.mockReset();
    Document.prototype.exitFullscreen = jest.fn();
    jest.useFakeTimers();
  }

  tearDown() {
    this.testRenderer.unmount();
    jest.runAllTimers();
    jest.useRealTimers();
    expect(this.consoleErrorSpy).not.toHaveBeenCalled();
  }

  act(func)  {
    TestRenderer.act(func);
  }

  render(jsx, options) {
    this.testRenderer = TestRenderer.create(jsx, options);
    return this.testRenderer;
  }

  renderWithDefaultNodeMock(jsx) {
    return this.render(jsx, this.defaultNodeMock);
  }

  async waitForComponent(component) {
    await waitForExpect(() => expect(
      this.testRenderer.root.findAllByType(component)
        .map(instance => ({ props: instance.props, type: instance.type }))).toHaveLength(1));
    return this.testRenderer.root.findByType(component);
  }

  async waitForComponentByProps(props) {
    await waitForExpect(() => expect(
      this.testRenderer.root.findAllByProps(props)
        .map(instance => ({props: instance.props, type: instance.type}))).toHaveLength(1));
    return this.testRenderer.root.findByProps(props);
  }

  async waitForComponentToLoad(component) {
    const instance = await this.waitForComponent(component);
    await waitForExpect(() => expect(instance.instance.state.hasLoaded).toBeTruthy());
    return instance;
  }

  setupBeforeAfter() {
    beforeEach(() => {
      this.setup();
    });
    afterEach(() => {
      this.tearDown();
    });
  }
}
  it('renders menu', () => {
    const menu = renderMenu();
    console.log(menu.instance);
    const menuList = menu.findByType(MenuList);
    console.log(menuList);
  });