Skip to main content
1 of 2

Is this Jest / Enzyme test sufficient or superfluous for the React component it is testing?

I'm trying to master testing. I struggle, conceptually, as to what should be tested.

  • Is this Jest / Enzyme test sufficient for this react component?

  • Is is too much?

  • Are there better practices that I should be implementing?

Here is my component.

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import {AverageText} from './index';

const Row = styled.div`
  display: flex;
  justify-content: center;
`;

const AvgSpeed = ({tests}) => {
  const downloadSpeeds = extractSpeeds(tests, 'download');
  const uploadSpeeds = extractSpeeds(tests, 'upload');
  const downloadAverage = getAverage(downloadSpeeds);
  const uploadAverage = getAverage(uploadSpeeds);
  return (
    <Row>
      <AverageText label="download" value={downloadAverage} />
      <AverageText label="upload" value={uploadAverage} />
    </Row>
  );
};

AvgSpeed.propTypes = {
  tests: PropTypes.object,
};

//returns average from array of numbers fixed at 1
function getAverage(array) {
  return (
    array.reduce((a, b) => {
      return a + b;
    }) / array.length
  ).toFixed(1);
}

//extracts float value from object property string value
function extractSpeeds(obj, property) {
  return Object.keys(obj).map(item => parseFloat(obj[item][property]));
}

//export to test
export {getAverage, extractSpeeds};

export default AvgSpeed;

My test

import React from 'react';
import AvgSpeed, {getAverage, extractSpeeds} from './AvgSpeed.js';
import {shallow, mount} from 'enzyme';
import renderer from 'react-test-renderer';

describe('AvgSpeed Component', () => {
  const inputObj = {
    1: {
      download: '22 mbs',
      upload: '9 mbs',
    },
    2: {
      download: '24 mbs',
      upload: '18 mbs',
    },
  };

  it('matches the snapshot', () => {
    const tree = renderer.create(<AvgSpeed tests={inputObj} />).toJSON();
    expect(tree).toMatchSnapshot();
  });

  describe('getAverage function', () => {
    it('returns the average from an array (fixed at 1)', () => {
      let input = [1, 2, 3];
      let output = '2.0';

      expect(getAverage(input)).toBe(output);

      //2,3,4
      input = input.map(n => (n += 1));
      output = '3.0';
      expect(getAverage(input)).toBe(output);

      //4,5,6
      input = input.map(n => (n += 2));
      output = '5.0';
    });
  });

  describe('extractSpeeds function', () => {
    it('return an array of float numbers', () => {
      const downloadIn = 'download';
      const uploadIn = 'upload';

      const downloadOut = [22, 24];
      const uploadOut = [9, 18];

      expect(extractSpeeds(inputObj, downloadIn)).toEqual(downloadOut);
      expect(extractSpeeds(inputObj, uploadIn)).toEqual(uploadOut);
    });
  });
});