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

jak*_*son 1 reactjs jestjs react-testing-library react-hooks testing-library

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

useEffect(() => {
  document.body.addEventListener('customEvent', onEvent);
}, []);
Run Code Online (Sandbox Code Playgroud)

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

sli*_*wp2 6

您可以使用fireEvent在 HTML 元素上调度CustomEventdocument.body。我在console.log()方法中添加了间谍来检查onEvent事件处理程序是否被调用。

\n

例如

\n

index.tsx:

\n
import React, { useEffect } from \'react\';\n\nexport function App() {\n  useEffect(() => {\n    document.body.addEventListener(\'customEvent\', onEvent);\n  }, []);\n\n  function onEvent(e) {\n    console.log(e.detail);\n  }\n\n  return <div>app</div>;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

index.test.tsx:

\n
import { App } from \'./\';\nimport { render, fireEvent } from \'@testing-library/react\';\nimport React from \'react\';\n\ndescribe(\'67416971\', () => {\n  it(\'should pass\', () => {\n    const logSpy = jest.spyOn(console, \'log\');\n    render(<App />);\n    fireEvent(document.body, new CustomEvent(\'customEvent\', { detail: \'teresa teng\' }));\n    expect(logSpy).toBeCalledWith(\'teresa teng\');\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

测试结果:

\n
 PASS  examples/67416971/index.test.tsx (8.781 s)\n  67416971\n    \xe2\x9c\x93 should pass (35 ms)\n\n  console.log\n    teresa teng\n\n      at console.<anonymous> (node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866:25)\n\n-----------|---------|----------|---------|---------|-------------------\nFile       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s \n-----------|---------|----------|---------|---------|-------------------\nAll files  |     100 |      100 |     100 |     100 |                   \n index.tsx |     100 |      100 |     100 |     100 |                   \n-----------|---------|----------|---------|---------|-------------------\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        9.638 s\n
Run Code Online (Sandbox Code Playgroud)\n

软件包版本:

\n
import React, { useEffect } from \'react\';\n\nexport function App() {\n  useEffect(() => {\n    document.body.addEventListener(\'customEvent\', onEvent);\n  }, []);\n\n  function onEvent(e) {\n    console.log(e.detail);\n  }\n\n  return <div>app</div>;\n}\n
Run Code Online (Sandbox Code Playgroud)\n