[英]Jest: Expect a function inside component to have been called
嗨,這段簡單的代碼受到https://testing-library.com/docs/example-react-formik/的啟發
import React from "react";
import { Formik, Field, Form } from "formik";
const sleep = (ms: any) => new Promise((r) => setTimeout(r, ms));
export const MyForm = () => {
const handleSubmit = async (values: any) => {
await sleep(500);
console.log(values);
};
return (
<div>
<Formik
initialValues={{
firstName: "",
}}
onSubmit={handleSubmit}
>
<Form>
<label htmlFor="firstName">First Name</label>
<Field id="firstName" name="firstName" placeholder="Jane" />
<button type="submit">Submit</button>
</Form>
</Formik>
</div>
);
};
和測試:
import React from "react";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MyForm } from "./MyForm";
test("rendering and submitting a basic Formik form", async () => {
const handleSubmit = jest.fn(); // this doing nothing
render(<MyForm />);
const user = userEvent.setup();
await user.type(screen.getByLabelText(/first name/i), "John");
await user.click(screen.getByRole("button", { name: /submit/i }));
await waitFor(() => expect(handleSubmit).toHaveBeenCalledTimes(1));
});
Console.log 打印了輸入的值: { firstName: 'John' }
,但測試失敗,因為它知道handleSubmit
未被調用。
這段代碼出了什么問題?
因為您沒有將模擬的handleSubmit
傳遞給<MyForm/>
組件。 您應該將它作為onSubmit
屬性傳遞給組件,並在內部handleSubmit
事件處理程序執行時調用它。
MyForm.tsx
:
export const MyForm = ({onSubmit}) => {
const handleSubmit = async values => {
await sleep(500)
submit(values)
}
return <div>...</div>
}
MyForm.test.tsx
:
test('rendering and submitting a basic Formik form', async () => {
const handleSubmit = jest.fn();
render(<MyForm onSubmit={handleSubmit} />);
await user.click(screen.getByRole('button', {name: /submit/i}));
await waitFor(() => expect(handleSubmit).toHaveBeenCalledTimes(1));
})
您看到官方示例和您的代碼之間的區別了嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.