【问题标题】:Fire (dispatch) custom event with react-testing-library使用 react-testing-library 触发(调度)自定义事件
【发布时间】:2021-05-06 11:12:32
【问题描述】:

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

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

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

【问题讨论】:

    标签: reactjs jestjs react-hooks react-testing-library testing-library


    【解决方案1】:

    您可以使用fireEventdocument.body HTML 元素上调度CustomEvent。我在 console.log() 方法中添加了 spy,以检查是否调用了 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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-17
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 2021-02-23
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多