1

我正在使用 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>吗?

在此处输入图像描述

4

2 回答 2

2

fireEvent(元素:ReactTestInstance,事件名称:字符串,...数据:数组):无效

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);

如果要检查 的onChange功能SegmentedControlIOS

fireEvent与尚未被fireEventapi别名的本机事件一起使用。

// you can omit the `on` prefix
fireEvent(getByTestId(testID), 'onChange');
于 2019-08-27T01:30:13.183 回答
0

这里发布了一个解决方案,我还没有尝试过,但我认为它看起来更正确 - 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,
    },
  });
});
于 2019-10-14T18:28:34.663 回答