vendredi 4 septembre 2020

React/Jest - Testing - Mock a click event object

So I have a simple react comp. which has a click event-handler. That uses the event handler obj. to pass it in another func. as argument like so:

ExampleComp

export default function App() {
  function onClick(e) {
    foo({e, bar: 'foo'}); // <== event object is passed as argument
  }
  return (
    <button onClick={onClick}>
    Click me
    </button>
  );
}

Now I want to basically test if foo has been called with that specific arguments. But I have a hard time in mocking the passed click event obj. For my react test setup Im NOT using Enzyme. I use: react-test-renderer, @testing-library/dom & @testing-library/react

My current test looks like:

import { fireEvent, waitFor } from '@testing-library/dom';
jest.mock('path/of/foo', () => ({
    foo: jest.fn(),
}));

describe('ExampleComp', () => {
    it('should call foo on click', async () => {
        const { queryByText } = render(
                <App />
        );

        const event = createEvent.click(queryByText('Click me'));
        fireEvent(queryByText('Click me'), click);

        await waitFor(() => {
            expect(foo).toHaveBeenCalledWith({
                e: event,
                bar: 'foo'
            });
        });

I get the error that the expected is diffrent from the received:

 - Expected
 + Received


Object {
        "foo": "bar",
    -   "e": MouseEvent {
    -     "isTrusted": false,
    +   "e": Class {
    +     "_dispatchInstances": null,
    +     "_dispatchListeners": null,
    +     "_targetInst": null,
    +     "altKey": null,
    +     "bubbles": null,
    +     "button": null,
    +     "buttons": null,
    +     "cancelable": null,
    +     "clientX": null,
    +     "clientY": null,
    +     "ctrlKey": null,
    +     "currentTarget": [Function currentTarget],
    +     "defaultPrevented": null,
    +     "detail": null,
    +     "dispatchConfig": null,
    +     "eventPhase": null,
    +     "getModifierState": [Function getEventModifierState],
    +     "isDefaultPrevented": [Function functionThatReturnsFalse],
    +     "isPropagationStopped": [Function functionThatReturnsFalse],
    +     "isTrusted": null,
    +     "metaKey": null,
    +     "movementX": [Function movementX],
    +     "movementY": [Function movementY],
    +     "nativeEvent": null,
    +     "pageX": null,
    +     "pageY": null,
    +     "relatedTarget": [Function relatedTarget],
    +     "screenX": null,
    +     "screenY": null,
    +     "shiftKey": null,
    +     "target": null,
    +     "timeStamp": [Function timeStamp],
    +     "type": null,
    +     "view": null,
        },

Does someone of you know how to properly mock the event handler object in react testing?

Aucun commentaire:

Enregistrer un commentaire