【问题标题】:Unit testing using Jest and Enzym in React Native在 React Native 中使用 Jest 和 Enzyme 进行单元测试
【发布时间】:2020-01-18 08:44:38
【问题描述】:

我怎样才能用 jest 和酵素找到组件内的元素?

假设我有 1 个父组件(Login)和 2 个子组件(Title 和 Form),所以在组件 Login 中,我想查找 Form 组件内是否有 TextInput 元素,或者其他可能是 Form 组件内的另一个元素,用玩笑和酶,那么我怎样才能通过 1 个单元测试(Login.test.js)得到它?

这是我的 ilustration 登录组件

<Login>
  <Title title='Login Page' />
  <Form 
     email={this.state.email}
     password={this.state.password}
  />
</Login>

标题组件

<Text>{this.props.title}</Text>

表单组件

<View>
  <TextInput value={this.props.email} placeHolder="Your Email" />
  <TextInput value={this.props.password} placeHolder="Your Password" />
</View>

这是我当前的 Login.test.js

import React from 'react';
import { shallow } from 'enzyme';
import Login from './Login';
import renderer from 'react-test-renderer';

describe('Login', () => {
  const wrapper = shallow(<Login />);
  const instaceOf = wrapper.instance();

  it('renders correctly', () => {
    const rendered = renderer.create(<Login />).toJSON();
    expect(rendered).toBeTruthy();
  });

  it('should render the Text Input Element', () => {
    let form = wrapper.find('Form');
    expect(form.find('TextInput"]')).toHaveLength(2);
  });
});

【问题讨论】:

    标签: react-native jestjs enzyme


    【解决方案1】:

    当您使用酶shallow 方法时,您只渲染组件的第一级。

    因此,声明:

    const wrapper = shallow(<Login />);
    

    只渲染TitleForm 组件,而不是它们的子组件。

    如果你想渲染所有的组件树,你应该使用mount。话虽如此,Login 组件的测试应该只测试它的第一个孩子。如果你想测试Form 组件渲染两个TextInput 组件,你应该在属于Form 组件的单元测试中这样做(而不是在Login 组件中)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-06
      • 2019-10-26
      • 2020-07-24
      • 2022-06-15
      • 2019-07-28
      • 2018-12-16
      • 2018-12-11
      • 2021-06-24
      相关资源
      最近更新 更多