0

我正在尝试测试使用Controllerfrom react-hook-formwith渲染的组件react-testing-library

          <Controller
            render={({ onChange, onBlur, value }) => (
              <IonInput
                onIonChange={onChange}
                onIonBlur={onBlur}
                value={value}
                type="text"
                data-testid="firstname-field"
              />
            )}
            name="firstName"
            control={control}
            defaultValue={firstName}
          />

当我使用一些模拟数据渲染组件时,默认值与预期一致。但是,当我开始更改值时,事件似乎没有触发。从这篇博文看来,ionic 导出了一组测试工具来处理 ionic 的自定义事件。在我的设置之后,setupTests.ts我尝试同时使用 RTU 的 ionFireEvent 和 fireEvent ,当我使用debug(). 我已经设置好了,所以我可以同时使用fireEventionFireEvent测试:

import { render, screen, wait, fireEvent } from "@testing-library/react";
import { ionFireEvent } from "@ionic/react-test-utils";


  // using RTL fireEvent - no change
  it("fires change event on firstname", () => {
    const { baseElement } = renderGolferContext(mockGolfer);
    const firstNameField = screen.getByTestId("firstname-field") as HTMLInputElement;
    fireEvent.change(firstNameField, { target: { detail: { value: "Jill" } } });
    expect(firstNameField.value).toBe("Jill");
  });

  // using IRTL ionFireEvent/ionChange - no change
  it("fires change event on firstname", () => {
    const { baseElement } = renderGolferContext(mockGolfer);
    const firstNameField = screen.getByTestId("firstname-field") as HTMLInputElement;
    ionFireEvent.ionChange(firstNameField, "Jill");
    expect(firstNameField.value).toBe("Jill");
  });    
    screen.debug(baseElement);

我也尝试将 data-testid 属性移动到控制器而不是这里IonInput建议的,结果是一样的:没有事件被触发。

以下是我正在使用的版本:

Using Ionic 5.1.1
@ionic/react-test-utils 0.0.3
jest  24.9
@testing-library/react 9.5
@testing-library/dom 6.16

这是我为演示而创建的一个仓库。

任何帮助将非常感激!

4

1 回答 1

1

这条线似乎不正确......

expect(firstNameField.value).toBe("Jill");

它应该在看,detail.value因为那是你设置的

expect((firstNameField as any).detail.value).toBe("Jill");

这是我的测试,

describe("RTL fireEvent on ion-input", () => {
  it("change on firstname", () => {
    const { baseElement, getByTestId } = render(<IonicHookForm />);
    const firstNameField = screen.getByTestId(
      "firstname-field"
    ) as HTMLInputElement;
    fireEvent.change(firstNameField, {
      target: { detail: { value: "Princess" } },
    });
    expect((firstNameField as any).detail.value).toEqual("Princess");
  });
});
于 2020-10-16T21:21:50.723 回答