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

1

6

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

Nellanellda answered 4/1, 2022 at 16:10 Comment(1)
You're just creating a new variable and setting it to be a jest.fn()... there's no connection to the component you want to test. Test the results of this function (eg. some changes in the rendered content), not the implementation of some function..Deterge
S
5

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;
Speech answered 4/1, 2022 at 16:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.