如何在使用Enzyme和Jest的单元测试中检查嵌套的React组件的值 [英] How to check the value of a nested React component in a unit test with Enzyme and Jest

查看:211
本文介绍了如何在使用Enzyme和Jest的单元测试中检查嵌套的React组件的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是测试的新手,我想访问const

I'm new in testing and I would like to access to a const

const Label = ({ intl, data }) => {
    if (data && data.length === 0) {
        return <div>{intl.translate('no_data')}</div>
    }
    return null
}

测试文件:

test('should return null when is data', () => {
    const component = shallow(<StatisticsGraph {...mockPropsForComponent} />)
    const label = component.find(Label)
    expect(label).toEqual(null)
})

变量mockPropsForComponent具有带有某些值的变量data. 我想知道测试通过的Label的值

The variable mockPropsForComponent has the variable data with some values. I want to know the value of Label for the test pass

推荐答案

有不同的解决方案,可以解决不同的问题.

There are different solutions, for different problems to solve.

Label组件隔离在其自己的文件中并导出.

Isolate the Label component in its own file and export it.

const Label = ({ intl, data }) => {
    if (data && data.length === 0) {
        return <div>{intl.translate('no_data')}</div>
    }
    return null
};

export default Label;

然后,分别进行测试.就像 Quentin提到的,组件只是可以调用的函数.

Then, test it individually. Like Quentin mentioned, a component is just a function you can call.

import Label from './Label';

test('should return null when there is data', () => {
  expect(Label({ data: ['anything'] })).toEqual(null);
})

测试组件的组成

由于您正在测试StatisticsGraph,并且您的Label组件没有可识别的选择器,因此您可以

Testing a composition of components

Since you're testing StatisticsGraph and that your Label component has no identifiable selector, you could use snapshots to make sure it's rendered correctly.

import React from 'react';
import { render } from 'enzyme';
import toJson from 'enzyme-to-json';

test('should return null when is data', () => {
    const wrapper = render(<StatisticsGraph {...mockPropsForComponent} />);
    expect(toJson(wrapper)).toMatchSnapshot();
});

手动测试组件

如果您真的要手动测试每个组件的零件,则可能需要更改Label以便于查找.

const Label = ({ intl, data }) => (
  <div className="label">
    {Boolean(data && data.length === 0) && intl.translate('no_data')}
  </div>
);

然后,应该找到该组件,并且可以使用 .isEmpty() 检查它是否有效.

Then, the component should be found and you could use .isEmpty() to check that it worked.

test('should return null when is data', () => {
    const component = shallow(<StatisticsGraph {...mockPropsForComponent} />);
    const label = component.find(Label);
    expect(label.isEmpty()).toBe(true);
});

这篇关于如何在使用Enzyme和Jest的单元测试中检查嵌套的React组件的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆