krsna
krsna

Reputation: 4353

How to test a function inside React functional component using jest.spyOn with React Testing Library

This is a simple React component. I'm using React Testing Library for unit testing components and I was not able to test the handleClick function of TestComponent using jest.spyOn(). Could anyone please help?

Component

import React from 'react';

const Button = (props) => (
  <button onClick={props.handleClick}> {props.text}</button>
);

const TestComponent = () => {
  const handleClick = () => {
    console.log('clicked!');
  };
  return (
    <div>
      <Button text="Test Button" handleClick={handleClick} />
    </div>
  );
};

export default TestComponent;

Test

  it('expect spy to be called', () => {
    const { getByText } = render(<TestComponent />);
    
    const spy = jest.spyOn(TestComponent, 'handleClick');
    
    const button = getByText('Test Button');
    fireEvent.click(button);
    expect(spy).toHaveBeenCalled();
  });

The error that I'm getting is below. I tried using TestComponent.prototype in jest.spyOn but that does not help either.

Cannot spy the handleClick property because it is not a function; undefined given instead

Upvotes: 2

Views: 1944

Answers (1)

Lin Du
Lin Du

Reputation: 102527

You can't spy handleClick event handler since it's defined in functional scope, it's private.

Your best test component behavior rather than implementation, such as what method is called inside the event handler, you should not go to mock and assert whether these methods are called, but what changes have occurred, such as what happens to the component, UI, DOM tree, etc.

But in your example, the handleClick event handler does not do anything, just calls console.log, then you can only assert whether the console.log is called indirectly assert whether the handleclick is called.

// arrange
const logSpy = jest.spyOn(console, 'log')
// act
// ...
// assert
expect(logSpy).toHaveBeenCalled()

Upvotes: 1

Related Questions