React / Jest-测试-模拟click事件对象

时间:2020-09-04 06:23:01

标签: javascript reactjs testing jestjs

所以我有一个简单的react comp。具有点击事件处理程序。使用事件处理程序obj。传递给另一个函数。作为这样的参数:

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

现在,我要基本上测试是否已使用该特定参数调用了foo。但是我很难模拟传递的单击事件obj。对于我的反应测试设置,我使用酶。我使用:react-test-renderer@testing-library/dom@testing-library/react

我当前的测试如下:

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

我得到一个错误,期望与接收到的不同:

 - 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,
        },

你们中有人知道如何在反应测试中正确模拟事件处理程序对象吗?

0 个答案:

没有答案