SegmentedControlIOS 上的 fireEvent

fireEvent on SegmentedControlIOS

我正在使用 react-native-testing-library - https://callstack.github.io/react-native-testing-library/docs/getting-started

我有一个 <SegmentedControlIOS> - https://facebook.github.io/react-native/docs/segmentedcontrolios

我要播放第一段。我这样做:

const testID = "SegmentedControl";
const stub = jest.fn();
const values = [{ label: "foo" }];
const { getByTestId } = render(
  <SegmentedControlIOS values={['foo', 'bar']} onChange={stub} testID={testID} />
);

expect(() => {
  getByTestId(testID);
}).not.toThrow();

fireEvent(getByTestId(testID), "change ", {
  nativeEvent: {
    value: values[0],
    selectedSegmentIndex: 0,
  },
});

但是我收到错误:

No handler function found for event: "change "

截图如下。任何人都知道如何在 <SegmentedControlIOS> 中按不同的段?

fireEvent(element: ReactTestInstance, eventName: string, ...data: Array): void

change 函数位于 fireEvent 对象中。使用方法如下:

版本 5 或更高版本:

fireEvent.change(getByTestId(testID), { target: { value: values[0],selectedSegmentIndex: 0 } });

版本 5 或更早版本:

const input = getByTestId(testID);
  input.value = values[0];
  input.selectedSegmentIndex = 0;
  fireEvent.change(input);

如果要查看SegmentedControlIOSonChange函数,

fireEvent 与尚未被 fireEvent api.

别名的本机事件一起使用
// you can omit the `on` prefix
fireEvent(getByTestId(testID), 'onChange');

这里贴出了一个解决方案,我还没试过,不过我觉得比较合适 - https://github.com/callstack/react-native-testing-library/issues/220#issuecomment-541067962

import React from "react";
import { SegmentedControlIOS } from "react-native";
import { fireEvent, render } from "react-native-testing-library";

const testID = "SegmentedControl";
const stub = jest.fn();
const values = [{ label: "foo" }];
const { getByTestId } = render(
  <SegmentedControlIOS
    values={["foo", "bar"]}
    onChange={stub}
    testID={testID}
  />,
);
it("sends events", () => {
  fireEvent(getByTestId(testID), "onChange", {
    nativeEvent: {
      value: values[0],
      selectedSegmentIndex: 0,
    },
  });
});