Ghubad
Ghubad

Reputation: 13

How do I test this stateless component with enzyme and jest?

DisplayTypes.tsx

import * as React from 'react';
import Checkbox from '../../Shared/Checkbox/Checkbox';

const displayTypes = ({
  appTypes,
  changed,
  userAssignedApplicatorTypes
}: any) => {
  return appTypes.map((applicatorType: any) => {
    let isChecked = userAssignedApplicatorTypes.find(
        (application: any) => 
           application.applicatorTypeName === applicatorType.name
    );
    return (
        <Checkbox
            id={applicatorType.id}
            key={applicatorType.id}
            changed={changed.bind(null, applicatorType.name)}
            element={applicatorType.name}
            isChecked={isChecked}
        />
    );
  });
};

export default displayTypes;

Here, I am displaying a Checkbox for every value in 'appTypes' and passing 'isChecked' value to each Checkbox.

The test coverage shows these lines are not covered. I want to test this part with enzyme and jest:

    let isChecked = userAssignedApplicatorTypes.find(
        (application: any) =>
            application.applicatorTypeName === applicatorType.name
    );

How do I do this?

Upvotes: 0

Views: 1158

Answers (1)

stealththeninja
stealththeninja

Reputation: 3791

When you describe checking the isChecked condition, I assume you're verifying based on how it binds to each Checkbox. This sounds like a good candidate for snapshot testing. The idea here is you setup your props, run the test which will create a snapshot file that you commit, and examine the serialized JSON in your snapshot file. The expect(tree).toMatchSnapshot() assertion will fail if the component output changes, at which point you can either fix the change that broke the test or update the snapshot if its output is correct.

DisplayTypes.spec.tsx

import React from 'react';
import renderer from 'react-test-renderer';
import displayTypes from './displayTypes';

describe('displayTypes', () => {
  it('should check when applicator type is found in user applicator types', () => {
    // arrange
    const props = {
      appTypes: [ ... ],
      changed: () => {},
      isChecked: false,
      userAssignedApplicatorTypes: [ ... ]
    };

    // act
    const tree = renderer
      .create(<displayType {...props}></displayType>)
      .toJSON();

    // assert
    expect(tree).toMatchSnapshot();
  });
}

Upvotes: 1

Related Questions