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

Time:01-05

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

CodePudding user response:

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;
  •  Tags:  
  • Related