【问题标题】:Testing onChange event with Jest用 Jest 测试 onChange 事件
【发布时间】:2020-03-08 14:32:31
【问题描述】:

根据我的代码覆盖率,我需要测试在我的onChange 事件中调用的函数。这实际上是我使用 useState 挂钩更新功能组件状态的地方。

这是我的组件:

const Component:React.FC<{}> = () => {
  const {value, setState} = useState('');
  return(
    <View>
      <CustomComponent 
        onChange={(value) => setState(value)}
      />
    </View>
  )
}

customComponent 是从 React Input 组件派生的组件。 当其中的文本发生更改时,它会调用 onChange 函数作为其属性与文本一起传递。这就是父组件的方式,它将文本输入的值设置为其状态,如上所示。

我的代码覆盖率返回此分析:

onChange={//(value) => setState(value)//}

// 之间的代码必须被覆盖。我真的不明白我怎么能涵盖这个。第一个想法是使用模拟函数,但我似乎找不到如何模拟它到 onChange 事件,因为我没有将任何东西作为道具传递给主组件。

【问题讨论】:

    标签: reactjs react-native jestjs enzyme react-hooks


    【解决方案1】:

    经过几次测试,我终于明白,覆盖并不是要求对 onChange 函数进行实际测试,而是要求评估的值。因此,这就是我正在做的事情:

    1. 获取 TextInput 子组件
    2. 更改其文本
    3. 评估其呈现的内容

    我在这里使用@testing-library/react-native 是因为它可以通过使用accessibilityLabel 来更轻松地选择树组件(它实际上让我了解了该道具的重要性)。
    下面是测试的样子:

    describe('Testing useState functions', () => {
        test('test', () => {
          //Rendering the component and its tree
          const { container, getByLabelText } = render(<SignupView />);
          //Extracting the child, username_input component with his accessibilityLabel
          const username_input = getByLabelText('username_input');
          const email_input = getByLabelText('email_input');
          //Fire a native changeText event with a specific value
          fireEvent.changeText(username_input, 'doe');
          fireEvent.changeText(email_input, 'doe@joe.com');
          //Checking the rendered value 
          expect(username_input.props.value).toEqual('doe');
          expect(email_input.props.value).toEqual('doe@joe.com');
        });
      });
    

    【讨论】:

      猜你喜欢
      • 2018-06-19
      • 2020-12-30
      • 2021-10-25
      • 2020-03-07
      • 1970-01-01
      • 2019-04-09
      • 2020-08-17
      • 2020-11-28
      • 1970-01-01
      相关资源
      最近更新 更多