loading...
Cover image for Day 7 of #100DaysOfCode: Learn Jest to test React components

Day 7 of #100DaysOfCode: Learn Jest to test React components

jenhsuan profile image Jen-Hsuan Hsieh ・2 min read

Introduction

Jest is a test library from facebook. We won't have to install it if the project is a CRA project (creat-react-app).

This article is to note an easy test for React components.

React component

  • This is our folders
    Alt Text

  • Suppose that we have a React component

import React from 'react'
import PropTypes from 'prop-types'

const FooterItem = ({externalLink, imageSrc, imageAltText}) => {
    return (
        <span className="btn-o">
            <a href={externalLink}>
                <img src={imageSrc} alt={imageAltText}/>
            </a>
        </span>
    )
}

FooterItem.propTypes = {
    imageSrc: PropTypes.string.isRequired,
    imageAltText: PropTypes.string.isRequired,
    externalLink: PropTypes.string.isRequired
}

export default FooterItem

Screenshot match test

  1. Create a test component (FooterItem.test.js) in the test folder
import React from 'react'
import FooterItem from '../components/FooterItem';
import twitter from '../images/twitter.png';
import renderer from 'react-test-renderer';

describe('<FooterItem/>', () => {
    test('Snapshot', () => {
      const component = renderer.create(<FooterItem imageSrc={twitter} imageAltText="twitter"
      externalLink="https://twitter.com/JenHsuanHsieh"/>);

      let snapshot = component.toJSON();
      expect(snapshot).toMatchSnapshot();

     });
});

2.Run the test

  • Type the following command in the terminal
npm test
  • Check the content from the terminal
    Alt Text

  • It will generate the snapshots folder.
    It will store screenshot files. When we run test second time and Jest will compare screen shots to make sure they are the same.
    Alt Text

  • If the screenshots are different, the test will fail.
    Alt Text

Coverage

  • Type the following command in the terminal
npm test -- --coverage
  • Check the content from the terminal Alt Text

Articles

There are some of my articles. Feel free to check if you like!

Posted on by:

jenhsuan profile

Jen-Hsuan Hsieh

@jenhsuan

6+ year work experience in the software engineering field. 2+ year work experience with front-end JavaScript framework like React.js, Knockout.js. and Microsoft solution.

Discussion

markdown guide