单元测试反应成分 - 笑话,酶

时间:2017-10-12 04:50:01

标签: javascript reactjs enzyme jest

我是单元测试反应组件。一个组件导入其他组件并使用其道具。这是jsx文件:

class First extends React.PureComponent {
    render() {
        const { name, isSelected, onClick } = this.props;
        const activeClass = isSelected ? styles.active : '';
        return (
            <div
                className={`${styles.first} ${activeClass}`}
                role="button"
                tabIndex={0}
                onClick={() => onClick(name)}
            >
                {name}
            </div>
        );
    }
}

First.propTypes = {
    name: PropTypes.string.isRequired,
    isSelected: PropTypes.bool,
    onClick: PropTypes.func,
};

export default First;

这是我导入此类的第二个类: 我

mport First from '../First/First';

const Second = ({ values, passedVal, onClick }) => {
    const second = values.map(vlaue =>
        <First
            key={value}
            name={value}
            isSelected={value === passedVal}
            onClick={onClick}
        />,
    );

    return (
        <div >
            {Second}
        </div>
    );
};

Second.propTypes = {
    values: PropTypes.arrayOf(PropTypes.string),
    passedVal: PropTypes.string,
    onClick: PropTypes.func,
};

export default FilterList;

这是我的测试。我想在我的测试中测试isSelected条件:

describe('Second - Unit test', () => {
    let props;
    let secondComponent;

    const second = () => {
        if (!secondComponent) {
            secondComponent = shallow(<Second {...props} />);
        }
        return secondComponent;
    };
      beforeEach(() => {
        props = Second.defaultProps;
        secondComponent = undefined;
    });

   it('verify value of isSelected ', () => {
             props.passedVal='value01';
             props.value=['value01'];
            console.log(props.isSelected);
           });

它给了我undefined,因为这是First类的道具。我如何在这里验证这个逻辑。需要首先制作实例然后检查?

2 个答案:

答案 0 :(得分:0)

props.isSelected将是未定义的,因为您没有向其传递任何值,并且它没有默认道具。

我认为不是:

props.passedVal='value01';
props.value=['value01'];

您想要使用:

secondComponent.setProps({
  passedVal: 'value01',
  values: ['value01']
});

请注意,在测试中,组件已经安装,因此为props对象分配新值实际上不会影响组件。然而,使用酶setProps会。您可以阅读更多相关内容:https://github.com/airbnb/enzyme/blob/master/docs/api/ShallowWrapper/setProps.md

此外,isSelectedFirst组件的支柱,因此请注意,当您尝试在测试中检查其值时。

答案 1 :(得分:0)

Wen使用shallow测试在组件上作为一个单元执行,并不间接断言子组件的行为。但是,您可以使用find检查子组件的属性,示例(未测试):

const wrapper = shallow(<First/>);
expect(wrapper.find(Second).first().prop('isSelected')).to.equal('yourValue');
相关问题