user10104341
user10104341

Reputation:

Enzyme | Conditionally check for props

I want to test that the correct component is being rendered when a prop has specific values true or false.

Here is the code:

/* 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;

And here is my test case: If the prop isValid is true, the render the Icon component with icon prop check else the other one.

Here is my test:

  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();
  });

The problem I think is in the check. Ι console.log it and get this ReactWrapper {}..

Any ideas on how to correctly do this...? Thanks!!

Upvotes: 0

Views: 869

Answers (2)

skyboyer
skyboyer

Reputation: 23705

from Enzyme'e docs find() expect EnzymeSelector to be passed. And this should be

  1. CSS-like selector(Icon[icon=check] in your case)
  2. constructor name(Icon)
  3. display name('Icon')
  4. object with properties

You are passing JSX element there so that finds nothing.

So I believe

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');
});

should work for you

Upvotes: 1

Bonjov
Bonjov

Reputation: 305

i have no idea why you doing this

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

if you need check prop

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();
});

Upvotes: 0

Related Questions