簡體   English   中英

開玩笑:預計組件內部的 function 已被調用

[英]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事件處理程序執行時調用它。

來看RTL官方formik測試示例

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM