reactjs - 如何為表單提交定義類型?(預期是 ObjectContaining,但得到的是 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.
嘗試了這篇 Medium 部落格文章中的步驟:https://medium.com/@evanteague/creating-fake-test-events-with-typescript-jest-778018379d1e
然而它們對那個使用情境來說過於具體。按照步驟嘗試重現它到目前為止也一直沒有效果。
如何為這個測試函數定義類型?
答案#1
面對完全相同的情況,我透過直接在 mock.calls 中檢查預期的 value 來處理它,就像這樣:
fireEvent.click(submitButton);
expect(handleSubmit.mock.calls[0][0].target.value).toEqual("some test value");
