1

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

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

我想触发自定义事件(喜欢fireEvent('customEvent')并测试是否onEvent被调用。

4

1 回答 1

2

您可以使用fireEvent在HTML 元素上调度CustomEvent 。document.body我在方法中添加了 spy 以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"
于 2021-05-06T12:14:28.113 回答