【问题标题】:How can I pass event properties to a customEvent using React Testing Library?如何使用 React 测试库将事件属性传递给 customEvent?
【发布时间】:2020-11-08 10:01:11
【问题描述】:

我正在尝试使用 RTL 测试组件,该组件使用 customEvent 来触发显示。给定这样的组件:

const Alerts = () => {
  const [alerts, setAlerts] = useState([]);

  const addAlert = (body, type = 'info', timeout = 7500) => {
    const key = nextIndex++;
    setAlerts([
      ...alerts,
      { key, body, type },
    ]);

    // Set a timer to remove the alert.
    setTimeout(() => {
      setAlerts(alerts.filter((alert) => alert.key !== key));
    }, timeout);
  };

  document.addEventListener(
    'newalert',
    ({ details:
      {
        body = '',
        type = '',
        timeout = 1000
      } = {}
    }) => {
      addAlert(body, type, timeout);
  });

  return (
    <>
      {alerts.map((alert) => <Alert {...alert} />)}
    </>
  );
};

我正在尝试这样测试:

test('An alert is rendered on a newalert event', () => {
  render(<Alerts  />);
  fireEvent(
    document,
    createEvent('newalert', document,
    {
      details: {
        body: 'Hello World!',
        type: 'info',
        timeout: 1000,
      }
    })
  );

  expect(screen.getByText('Hello world'));
});

它正在按预期触发自定义事件,但是没有任何属性(详细信息、正文、类型或超时)被传递给事件。我错过了什么?

【问题讨论】:

标签: reactjs react-testing-library custom-events


【解决方案1】:

需要将事件构造函数的名称作为第四个参数传递,才有效!

createEvent(
      'newalert',
      document,
      {
        detail: {
          body: 'Hello World!',
          type: 'info',
          timeout: 1000,
        }
      },
      { EventType: 'CustomEvent' }
    )
  );

【讨论】:

  • 类型已在 testing-library-dom 7.24.4 中修复。
  • 为什么叫detail?为什么我不能给它任何我想要的名字?喜欢数据?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-04
  • 2020-11-17
  • 1970-01-01
  • 2010-10-13
  • 1970-01-01
相关资源
最近更新 更多