SegmentedControlIOS上的fireEvent

时间:2019-08-26 23:59:40

标签: react-native react-testing-library react-native-testing-library

我正在使用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>中的不同句段吗?

enter image description here

2 个答案:

答案 0 :(得分:2)

  

fireEvent(元素:ReactTestInstance,eventName:字符串,...数据:   数组):无效

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的{​​{1}}功能,

SegmentedControlIOS与没有fireEvent api别名的本机事件一起使用。

fireEvent

答案 1 :(得分: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,
    },
  });
});