mikeborozdin / jest-react-hooks-shallow

Bringing React Hooks to shallow rendering
ISC License
114 stars 9 forks source link

How to run useEffect cleanup - Help #24

Closed aashayamballi closed 4 years ago

aashayamballi commented 4 years ago

The cleanup functions are only called before invoking the same effect again.

Thank you for this library! can you please demonstrate "cleanup functions are only called before invoking the same effect again." I've gone through the demo but was not able to achieve it. Below is the sample useEffect I've in my project

 useEffect(() => {
        dispatch({
            type: SET_RESOLUTION_STATUS_COUNT_BAR_CHART_FETCHING_DATA,
            payload: true,
        });
        dispatch(getResolutionStatusCount([]));
        return () => {
            const barChartPayload = {
                barChartData: [],
                barChartCategories: [],
                resolution_status_environment: [],
            };
            dispatch({
                type: SET_RESOLUTION_STATUS_COUNT_BAR_CHART,
                payload: barChartPayload,
            });
        };
    }, []);

and Below is the test cases what I have

const setup = (props = {}) => {
    return shallow(<ResolutionCount {...props} />)
}

test("dispatch actions on unmount ", () => {
        mockState({
            generalReducer: {
                dateRangePicker: {
                    startDate: "",
                    endDate: "",
                }
            }
        });

        setup({ componentUsedIn: "range picker" });

        expect(mockDispatch).toHaveBeenNthCalledWith(1, {
            type: "SET_RESOLUTION_STATUS_COUNT_BAR_CHART_FETCHING_DATA",
            payload: true
        });

        expect(mockDispatch).toHaveBeenNthCalledWith(2, expect.any(Function))

Could you please tell me how would I achieve component unmount here.

Thank you

mikeborozdin commented 4 years ago

Hi @aashayamballi,

Thank you for submitting an issue. Unfortunately, it is not currently possible. The library doesn't have an ability to hook into the component lifecycle. It doesn't know when the unmount() is called, hence it cannot trigger the cleanup function.

The cleanup functions are only triggered when the same effect is called multiple times.

But there's an interesting discussion about the same problem in this issue - https://github.com/mikeborozdin/jest-react-hooks-shallow/issues/8. So I'm going to close this one as a duplicate. But I'm very likely to implement an idea suggested in this post