使用 react-testing-library 触发(调度)自定义事件

Fire (dispatch) custom event with react-testing-library

有没有办法用 react-testing-library 触发自定义事件?我在他们的文档中找不到这样的例子。

useEffect(() => {
  document.body.addEventListener('customEvent', onEvent);
}, []);

我想触发自定义事件(例如 fireEvent('customEvent') 并测试是否调用了 onEvent

您可以在 document.body HTML 元素上使用 fireEvent to dispatch a CustomEvent。我将间谍添加到 console.log() 方法以检查是否调用了 onEvent 事件处理程序。

例如

index.tsx:

import React, { useEffect } from 'react';

export function App() {
  useEffect(() => {
    document.body.addEventListener('customEvent', onEvent);
  }, []);

  function onEvent(e) {
    console.log(e.detail);
  }

  return <div>app</div>;
}

index.test.tsx:

import { App } from './';
import { render, fireEvent } from '@testing-library/react';
import React from 'react';

describe('67416971', () => {
  it('should pass', () => {
    const logSpy = jest.spyOn(console, 'log');
    render(<App />);
    fireEvent(document.body, new CustomEvent('customEvent', { detail: 'teresa teng' }));
    expect(logSpy).toBeCalledWith('teresa teng');
  });
});

测试结果:

 PASS  examples/67416971/index.test.tsx (8.781 s)
  67416971
    ✓ should pass (35 ms)

  console.log
    teresa teng

      at console.<anonymous> (node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866:25)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.tsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.638 s

包版本:

"@testing-library/react": "^11.2.2",
"react": "^16.14.0"