首页 > 解决方案 > FireEvent.click TypeError:无法读取未定义的属性“单击”

问题描述

我正在使用 React 测试库,并且我有一个嵌套在一堆圆顶元素中的标签。我上面有一个测试 ID,我可以看到它使用正确的节点进行调试。但是当我运行我的测试时。

import { render, cleanup } from '@testing-library/react';

test('bla', () => {
  const { fireEvent, getByTestId, debug } = render(
    <Group>
      <Menu items={items} />
    </Group>
  );

  const viewMore = getByTestId('button');
  console.log('viewMore = ', viewMore);
  // debug(viewMore);
  fireEvent.click(viewMore, {});
});

我收到以下错误。

TypeError: Cannot read property 'click' of undefined

为什么这会告诉我无法读取属性“点击”?

我的带有按钮类的标签位于我的菜单组件内,该组件在 Group 内呈现。

这是viewMore返回的精简版本。

 viewMore =  HTMLAnchorElement {
        '__reactInternalInstance$6ct8li9ulz6': 
         FiberNode {
           tag: 5,
           key: null,
           elementType: 'a',
           type: 'a',
           stateNode: [Circular],
           return: 
            FiberNode {
              tag: 5,
              key: null,
              elementType: 'div',
              type: 'div'},
           child: null,
           sibling: null,
           index: 1,
           ref: null,
           pendingProps: 
            { href: '#',
              className: 'button',
              'data-testid': 'button',
              onClick: [Function: action],
              children: 'VIEW MORE...' },
           memoizedProps: 
            { href: '#',
              className: 'button',
              'data-testid': 'button',
              onClick: [Function: action],
              children: 'VIEW MORE...' }
        '__reactEventHandlers$6ct8li9ulz6': 
         { href: '#',
           className: 'a-tag',
           'data-testid': 'button',
           onClick: [Function: action],
           children: 'VIEW MORE...' } }

标签: reactjsreact-testing-library

解决方案


fireEvent不是来自render您需要从 RTL 导入它:

import { fireEvent } from '@testing-library/react'

推荐阅读