如何定义表单提交的类型? (期待 ObjectContaining 而不是获得 SyntheticEvent)

How to define type for form submit? (expecting ObjectContaining instead getting SyntheticEvent)

使用 typescript、react、jest 和 react-testing-library

使用了以下代码:

Form.tsx

export interface IFormProps {
  handleSubmit: (event: FormEvent<HTMLFormElement>) => void;
}

const Form: React.FC<IFormProps> = (props: IFormProps) => {
  return (
    <form onSubmit={props.handleSubmit}>
      <FormControl>
        <Input name="myInput" data-testid="myInputId" />
      </FormControl>
      <Button type="submit" data-testid="mySubmitButton">Submit form</Button>
    </form>
  )
};

Page.tsx

class Page extends React.Component {
  //...
  public handleSubmit = <T extends React.FormEvent>(event: T) => {
    event.preventDefault();
    // do stuff with it
  }
  //...
}

form.test.tsx

it('submits the form data ', () => {
  const handleSubmit = jest.fn();

  const { getByTestId } = render(<Form handleSubmit={handleSubmit} />);

  const input = getByTestId('myInputId') as HTMLInputElement;
  const submitButton = getByTestId('mySubmitButton') as HTMLButtonElement;

  fireEvent.change(input, {
      target: { value: 'some test value' }
    });

  // API: fireEvent(node: HTMLElement, event: Event)
  fireEvent.click(submitButton);

  expect(handleSubmit).toHaveBeenCalledTimes(1);

  /* 
   * the following outputs the failed test output below 
   */
  expect(handleSubmit).toHaveBeenCalledWith(
    expect.objectContaining({
      "value": "some test value",
    })
  );
}

输出:

    - Expected
    + Received

    - ObjectContaining {
    -   "value": "some test value",
    + SyntheticEvent {
    +   "_dispatchInstances": null,
    +   "_dispatchListeners": null,
    +   "_targetInst": null,
    +   "bubbles": null,
    // ...etc.

尝试了这篇中型博文中的步骤:https://medium.com/@evanteague/creating-fake-test-events-with-typescript-jest-778018379d1e

但是它们对于那个用例来说太具体了。到目前为止,尝试按照步骤重现它也没有奏效。

如何为这个测试函数定义类型?

面对完全相同的情况,设法处理它直接在 mock.calls 中检查预期的 value,就像这样:

fireEvent.click(submitButton);
expect(handleSubmit.mock.calls[0][0].target.value).toEqual("some test value");