首页 > 解决方案 > 在 React Native 中使用 Jest 和 Enzym 进行单元测试

问题描述

如何用玩笑和酶找到组件内的元素?

假设,我有 1 个组件父组件(登录)和 2 个子组件(标题和表单),所以在组件登录中,我想找到表单组件内是否有 TextInput 元素,或者其他可能是表单组件内的另一个元素,开玩笑和酶,那么我怎样才能通过 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-nativejestjsenzyme

解决方案


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

因此,声明:

const wrapper = shallow(<Login />);

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

如果要渲染所有组件树,则应mount改为使用。话虽如此,您的Login组件的测试应该只测试它的第一个孩子。如果要测试该Form组件呈现两个TextInput组件,则应在属于Form组件的单元测试中进行(而不是在Login组件中)。


推荐阅读