Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I write a unit test to call a function inside useEffect?

I am trying to write a unit test using jest and react testing library. I want to test a function call inside the useEffect hook, but my test is not working. What do I need to do to pass the test successfully?

  useEffect(() => {
    getActiveFilters(filterValue);
    // eslint-disable-next-line
  }, [filterValue, dictionaries]);

Here my test

  it('should call the [getActiveFilters] function', async () => {
    const getActiveFilters = jest.fn();
    await waitFor(() => expect(getActiveFilters).toHaveBeenCalled());
  });

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I know that it is hard to mock function in component. You should using spy(test double) for some module. The way that check rendering elements in document properly is also good idea.

Here is my example.

Test Code

    it('axios spy and rendering test', async () => {

        const spyAxios = jest.spyOn(axios, 'get').mockResolvedValue({
            data: 'Junhyunny'
        });

        render(<SecondAuth />);

        await waitFor(() => {
            expect(screen.getByText('Sir Junhyunny')).toBeInTheDocument();
        });
        expect(spyAxios).toHaveBeenNthCalledWith(1, 'http://localhost:8080', {
            params: {}
        });
    });

Component

import {useEffect, useState} from "react";
import axios from "axios";

const SecondAuth = () => {

    const [name, setName] = useState('');

    useEffect(() => {
        axios.get('http://localhost:8080', {
            params: {}
        }).then(({data}) => {
            setName(data);
        });
    }, []);

    return (
        <div>
            <p>Sir {name}</p>
        </div>
    );

};

export default SecondAuth;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading