3

Is there a way to fire a custom event with react-testing-library? I couldn't find such example in their docs.

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

I want to fire custom event (sth. like fireEvent('customEvent') and test if onEvent was called.

1 Answer 1

8

You can use fireEvent to dispatch a CustomEvent on document.body HTML element. I added spy to console.log() method to check if the onEvent event handler is called or not.

E.g.

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');
  });
});

test result:

 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

package versions:

"@testing-library/react": "^11.2.2",
"react": "^16.14.0"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.