Part 6 Testing React Applications – Testing click method

Hi, continuing with our posts about testing React applications today we are going to see how change props in our test case using the Enzyme method called setProps()

So the definition for setProps() is that “A method that sets the props of the root component, and re-renders. Useful for when you are wanting to test how the component behaves over time with changing props.”



Ok, also we have a onClick handler method in our component, so we want to be sure that when the user click on a todo in a list then the “mockFunction” will be triggered.

So we can simulate a click with jest like this

// Simulating our onClick event
  const mockFn = jest.fn();

Then we can use the jest method called toHaveBeenCalledTimes() that is use to ensure that a mock function got called exact number of times.

  // 4 Individual Test case
  it("should call onClick handler when todo component is clicked", () => {
    // shallow() method is from Enzyme
    // and create an instance of <Todo /> component
    const component = shallow(<Todo {...initialProps} />);

    // Simulating onClick method
    component.simulate("click"); // First click on the component
    component.simulate("click"); // second click on the component

    // Assertions
    expect(mockFn).toHaveBeenCalledTimes(2); // expect(), mockFn and toHaveBeenCalledTimes are from Jest


By Cristina Rojas.