Garrett Daniel DeMeyer
Garrett Daniel DeMeyer

Reputation: 931

How can I test an onClick line of a React component using Jest?

I am learning React and I am currently trying Jest/testing. I am starting tests on a small project and I want to get 100% code coverage. Here's what I have.

component:

import React from 'react';

function Square(props) {
    const className = props.isWinningSquare ?
        "square winning-square" :
        "square";
    return (
        <button
            className={className}
            onClick={() => props.onClick()}
        >
            {props.value}
        </button>
    );
}

export default Square

tests:

import React from 'react';
import Square from '../square';
import {create} from 'react-test-renderer';

describe('Square Simple Snapshot Test', () => {
    test('Testing square', () => {
        let tree = create(<Square />);
        expect(tree.toJSON()).toMatchSnapshot();
    })
})

describe('Square className is affected by isWinningSquare prop', () => {
    test('props.isWinningSquare is false, className should be "square"', () =>{
        let tree = create(<Square isWinningSquare={false} />);

        expect(tree.root.findByType('button').props.className).toEqual('square');
    }),
    test('props.isWinningSquare is true, className should be "square winning-square"', () =>{
        let tree = create(<Square isWinningSquare={true} />);

        expect(tree.root.findByType('button').props.className).toEqual('square winning-square');
    })

})

The line indicated as "uncovered" is

onClick={() => props.onClick()}

What is the best way to test this line? Any recommendations?

Upvotes: 3

Views: 10521

Answers (2)

James
James

Reputation: 82096

You would use a Mock Function

test('props.onClick is called when button is clicked', () =>{
  const fn = jest.fn();
  let tree = create(<Square onClick={fn} />);
  // Simulate button click
  const button = tree.root.findByType('button'):
  button.props.onClick()
  // Verify callback is invoked
  expect(fn.mock.calls.length).toBe(1);
});

Also, for what it's worth, in your component you can assign the onClick handler straight to the prop i.e.

<button
  className={className}
  onClick={props.onClick}
>

Upvotes: 8

Radosław Miernik
Radosław Miernik

Reputation: 4094

Simply target the element and call its handler:

tree.root.findByType('button').props.onClick();

Upvotes: 0

Related Questions