Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spy on method inside a React Functional Component?

I have this functional component.

Search.js


function Search() {
  const [term, setTerm] = useState('sun');

  function handleOnChange(e) {
    if (!e.target.value) {
      return false;
    }
    setTerm(e.target.value);
    return true;
  }

  return <input type="text" onChange={handleOnChange} placeholder="Search" />
}

Search.test.js

import { render, fireEvent } from '@testing-library/react';
import Search from '.';

describe('when type a valid term', () => {
  it('update the state', () => {
    const { getByPlaceholderText } = render(<Search />;

    // this doesn't work. The handleOnChange method is private. How to deal with this?
    const handlerSpy = jest.spyOn(Search, 'handleOnChange');

    fireEvent.click(getByPlaceholderText(/search/i), { target: { value: 'moon' } });

    expect(handlerSpy).toHaveReturnedWith(true);
  });
});


I don't know if I'm trying the wrong approach. I just need to test what happens if the user type an empty term. Appreciate any suggestion.

like image 603
Pablo Darde Avatar asked Oct 23 '25 15:10

Pablo Darde


1 Answers

Please, if you have a better answer left it here. After a search for different approaches, I realized another way to test it.

First, I attached the current state to the value attribute of my search field.

This way, I can check if the attribute value of my search field changes accordingly


import { render, fireEvent } from '@testing-library/react';
import Search from '.';

describe('when type a valid term', () => {
  it('update the state', () => {
    const { getByPlaceholderText } = render(<Search />);
    const inputField = getByPlaceholderText(/search/i);
    fireEvent.change(inputField, { target: { value: 'moon' } });

    expect(inputField).toHaveValue('moon');
  });
});

It's possible to write a snapshot test as well.

like image 85
Pablo Darde Avatar answered Oct 26 '25 04:10

Pablo Darde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!