【问题标题】:React-testing-library with Ionic v5 (react) and react-hook-form- change events do not fire带有 Ionic v5 (react) 的 React-testing-library 和 react-hook-form-change 事件不会触发
【发布时间】:2020-10-13 22:06:10
【问题描述】:

我正在尝试使用react-hook-formreact-testing-library 测试使用Controller 呈现的组件

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

当我使用一些模拟数据渲染组件时,默认值与预期一致。但是,当我开始更改值时,事件似乎没有触发。从this 博客文章看来,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 建议的 here,结果相同:没有触发任何事件。

这是我正在使用的版本:

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

Here is a repo 我是为了演示而创建的。

任何帮助将不胜感激!

【问题讨论】:

  • 你有什么小项目吗?
  • @AaronSaunders 编辑了我的问题以包含指向 repo 的链接

标签: ionic-framework react-testing-library ionic-react


【解决方案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");
  });
});

【讨论】:

    猜你喜欢
    • 2021-07-28
    • 2023-01-31
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 2022-01-23
    • 2021-09-14
    相关资源
    最近更新 更多