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
被调用。
您可以使用fireEvent在 HTML 元素上调度CustomEventdocument.body
。我在console.log()
方法中添加了间谍来检查onEvent
事件处理程序是否被调用。
例如
\nindex.tsx
:
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)\nindex.test.tsx
:
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软件包版本:
\nimport 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
归档时间: |
|
查看次数: |
8578 次 |
最近记录: |