Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing Jest in Reactjs Component state

Hello :) I'm starting to learn Unit Testing using JEST & Enzyme

on my version (already done) of "Color Guessing Game" using with Reactjs, but when I started to test my Square Component I can't even test my color state value and my color state when clicked (clickSquare function)...

and I can't find much resources about it, can you see what's wrong, and how can I test my Square Component?

Square.js Component:

import React, { Component } from 'react';



class Square extends Component {




constructor(props) {
    super(props);
    this.state = {
      color: undefined
    }
    this.clickSquare = this.clickSquare.bind(this);
  }

  componentDidMount() {
    if (this.props.color) {
      this.setState({
        color: this.props.color
      })
    }
  };

  componentWillReceiveProps(props) {
    //results in the parent component to send updated props,, 
    //whenever the propositions are updated in the parent, runs this
    //to update the son as well
    this.setState({
      color: props.color
    })

  }

  clickSquare() {
    if (this.state.color === this.props.correctColor) {
      this.props.gameWon(true);
      console.log('correct', this.state.color)

    } else {
      this.setState({
        color: 'transparent'
      })
      //    this.props.gameWon(false);
      console.log('wrong')

    }
  };

  render() {

    return (
      <div className='square square__elem'
        style={{ backgroundColor: this.state.color }}
        onClick={this.clickSquare}>
      </div>
    );
  }
};

export default Square;

Square.test.js Testing:

import React from 'react';

import Square from '../components/Square/Square';

import { shallow, mount } from 'enzyme';


describe('Square component', () => {

    let wrapper;
    beforeEach(() => wrapper = shallow(
        <Square
            color={undefined}
            clickSquare={jest.fn()}
        />
    ));


    it('should render correctly', () => expect(wrapper).toMatchSnapshot());

    it('should render a <div />', () => {
        expect(wrapper.find('div.square.square__elem').length).toEqual(1);
    });

    it('should render the value of color', () => {
        wrapper.setProps({ color: undefined});
        expect(wrapper.state()).toEqual('transparent');
      });

});

Expected value to equal: "transparent" Received: {"color": undefined}

Difference:

  Comparing two different types of values. Expected string but received object.
like image 741
AFAF Avatar asked Feb 26 '19 19:02

AFAF


People also ask

How do you mock state of a component in Jest?

To enable us to mock useState, we use React. useState (line #5) instead of using the usual named import (i.e. import { useState } from 'react'). Below is our Jest unit test for the component. Before rendering the component for testing, we create a constant 'setStateMock' and mock it with a jest function jest.

How would you test the React components using Jest and enzymes?

Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.

Is Jest good for React?

If you are new to React, we recommend using Create React App. It is ready to use and ships with Jest!


1 Answers

Well, you're not so far from the solution. :)

The only issue is that between the parentheses in the expression wrapper.state(), you don't pass any argument - that's why you receive the whole object instead of a single value. That being said, you should do the following in this case:

it('should render the value of color', () => {
   wrapper.setProps({ color: undefined});
   expect(wrapper.state('color')).toEqual('transparent');
});

Notice the usage of wrapper.state('color').


EDIT

Based on your comment below, I didn't realize that the transparent value is set via a click event.

Here is the full test suite that should be verified by Jest:

import React from 'react';
import { shallow } from 'enzyme';
import Square from '../components/Square/Square';

describe('<Square />', () => {
   let wrapper;

   beforeEach(() => {
      wrapper = shallow(<Square color={undefined} />); // Here it's not necessary to mock the clickSquare function.
   });

   it('should render the value of color', () => {
      wrapper.setProps({ color: undefined });
      wrapper.find('div').simulate('click'); // Simulating a click event.

      expect(wrapper.state('color')).toEqual('transparent');
   });
});
like image 187
zsgomori Avatar answered Oct 05 '22 09:10

zsgomori