酵素|有条件地检查道具

时间:2019-02-20 11:40:47

标签: javascript reactjs unit-testing jestjs enzyme

我想测试当道具具有特定值truefalse时是否渲染了正确的组件。

代码如下:

/* eslint-disable react/default-props-match-prop-types */
import React, { Fragment } from 'react';
import moment from 'moment';
import ILicense from 'dto/ILicense';

import Icon from 'components/Icon';

export interface Props {
  license?: ILicense;
}

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const LicenseInfo = <T extends object>({ license }: Props & T) => (
  <Fragment>
    {license ? (
      <Fragment>
        <div className="py-5 mx-3">
          {license.isValid? (
            <div>
              <Icon icon="check" className="fa-lg text-success mr-2" />
              License is Valid
            </div>
          ) : (
            <div>
              <Icon icon="exclamation-circle" className="fa-lg text-danger mr-2" />
              License has expired
            </div>
          )}
      </Fragment>
    ) : null}
  </Fragment>
);

LicenseInfo.defaultProps = {
  clientId: '',
  expiry: null,
  isValid: true,
};

export default LicenseInfo;

这是我的测试用例:If the prop isValid is true,使用图标道具check渲染Icon组件,另一个渲染。

这是我的考试:

  it('expect to show check Icon when license.isValid prop is true', () => {
    const wrapper = mount<LicenseInfo>(<LicenseInfo isValid="true">Test</LicenseInfo>);
    const check = wrapper.find(<Icon icon="check" />).props;
    console.log(check);
    expect(check).toBeTruthy();
  });

我认为问题出在check中。 Ιconsole.log,并获取此ReactWrapper {} ..

关于如何正确执行此操作的任何想法...?谢谢!

2 个答案:

答案 0 :(得分:2)

酶文档find()

期望EnzymeSelector被通过。这应该是

  1. 类似CSS的选择器(在您的情况下为Icon[icon=check]
  2. 构造函数名称(Icon
  3. 显示名称('Icon'
  4. 具有属性的对象

您正在向其中传递JSX元素,因此一无所获。

所以我相信

it('expect to show check Icon when license.isValid prop is true', () => {
  const wrapper = mount<LicenseInfo>(<LicenseInfo isValid="true">Test</LicenseInfo>);
  const iconType = wrapper.find(Icon).prop('icon');
  expect(iconType).toEqual('check');
});

应该为您工作

答案 1 :(得分:0)

我不知道你为什么要这么做

const check = wrapper.find(<Icon icon="check" />).props;

如果您需要支票道具

it('expect to show check Icon when license.isValid prop is true', () => {
  const wrapper = mount<LicenseInfo>(<LicenseInfo isValid="true">Test</LicenseInfo>);
  const check = wrapper.props().isValid;
  console.log(check);
  expect(check).toBeTruthy();
});