Part 5 Testing React Applications – Testing props

Florence, Metropolitan City of Florence, Italy

Hi, continuing with the posts we can test the props because in our code we are passing some props, so let’s test some things with the props. 

Let suppose that is the first time that you want to look for props and you don’t actually know what methods are available in this case we can use the Enzyme method called .props() to see what things are available to us and another thing that we can do is insert console.log in our code.

console.log(component.props());

Result:  so we have the onClick method, the style and the children props

So if we want to test the component props we can use the .props() method like this:

// Dependencies
import React from 'react'

// Components
import Todo from './Todo';

// Enzyme Dependencies
import { configure, shallow, mount } from 'enzyme';

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });

// Test Suite
describe("<Todo /> component Unit Tests", () => {
  // Simulating our onClick event
  const mockFn = jest.fn();
  const props = {
    onClick: mockFn,
    completed: false,
    text: "do laundry"
  }

  // 1 Individual Test Case
  it("should render 1 <Todo /> component", () => {

    // Using shallow from enzyme and passing all the 
    // props to the component
    const component = shallow(<Todo {...props} />)

    // Assertions
    expect(component).toHaveLength(1); // .toHaveLength is from Jest
    // the component will have only 1 HTML <li>
    expect(component.find("li")).toHaveLength(1); 
  });

  // 2 Individual Test Case
  it("should render props correctly", () => {

    // Using shallow from enzyme and passing all 
    // the props to the component
    const component = shallow(<Todo {...props} />)

    // To know the component props
    console.log(component.props());

    // Assertions
    // testing the children prop to be equal to this string
    expect(component.props().children).toEqual("do laundry");
  });

});

Result: my 2 tests passed

But if we change the prop text like this: “xxxx” then my test case will fail

Result: if you see the “x” cross in red color means which test is failing.

By Cristina Rojas.