有没有办法用react-testing library触发一个自定义事件?我在他们的文档中找不到这样的例子。
useEffect(() => {
document.body.addEventListener('customEvent', onEvent);
}, []);我想触发自定义事件(某事物例如fireEvent('customEvent')并测试是否调用了onEvent。
发布于 2021-05-06 20:14:28
您可以使用fireEvent在document.body HTML元素上分派CustomEvent。为了检查是否调用了onEvent事件处理程序,我在console.log()方法中添加了spy。
例如。
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"https://stackoverflow.com/questions/67416971
复制相似问题