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

1633 views reactjs
4

DisplayTypes.tsx

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

const displayTypes = ({
  appTypes,
  changed,
  isChecked,
  userAssignedApplicatorTypes
}: any) => {
  return appTypes.map((applicatorType: any) => {
    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:

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

How do I do this?

answered question

isChecked is passed in as a prop, then reassigned from the .find() result. Probably want to address this (though I doubt it's related to the question).

1 Answer

7

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 is you setup your props, run the test which will create a snapshot file that you commit the file, 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();
  });
}

posted this

Have an answer?

JD

Please login first before posting an answer.