Nick
Nick

Reputation: 2559

How to test a function that you don't have direct access to

I'm trying to test a dispatch function destructured from useReducer.

My dispatch function is created within my component so, as far as I can tell, I'm not able to expect(dispatch).toHaveBeenCalledWith({...}) like I normally would.

My Component looks something like this:

const reducer = (state, action) => {
    switch (action.type) {
        case 'MY_ACTION':
            return { ...state, myError: action.payload };
    }
};

const Container = ({ someProp, anotherProp, aThirdProp }) => {

    // This hook only works at this level of my application

    const onlyAvailableInsideContainer = useonlyAvailableInsideContainer();



    // Due to the above my initial state needs to be created here

    const initialState = {
        initialStateArr: [],
        someProp,
        myError: null,
        aThirdProp,
        anotherProp,
        onlyAvailableInsideContainer,
    };



    // Which means I need to extract my state and dispatch functions within the Container also

    const [state, dispatch] = useReducer(reducer, initialState);

    const { fieldProps, formProps, errors } = someHook(
        hookConfig(state, dispatch, aThirdProp, onlyAvailableInsideContainer),
    );

    return (
        <div className="dcx-hybrid">
            <MyContext.Provider
                value={{ state, dispatch, fieldProps, formProps, errors }}
            >
                <SomeChildComponent />
            </MyContext.Provider>
        </div>
    );
};

I need to test the dispatch function destructured from useReducer, but am unable to access it (as far as I can tell).

Ideally my initial state and useReducers would be created exclusively from my component, but I need information that is only accessible from within.

Something like this is what I think I need to do, but I don't know how to format the test in a way that it knows what I'm trying to do.

function renderContainer(props) {
    // eslint-disable-next-line react/jsx-props-no-spreading
    const utils = render(<Container {...props} />);

    return {
        ...utils,
    };
}

test('an error will be disatched when the endpoint returns a 4xx status', async () => {
    fetchMock.post('/api/myendpoint', 400);

    const component = renderContainer();

    await act(async () => {
        fireEvent.click(component.getByText('Continue'));
    });

    expect(dispatch).toBeCalledWith({
        type: 'MY_ACTION',
        payload: 'Some error message.',
    });
});

Upvotes: 3

Views: 495

Answers (1)

adel
adel

Reputation: 3507

try spying on useReducer like this:

const dispatch= jest.fn();
const useReducerMock= (reducer,initialState) => [initialState, dispatch];
jest.spyOn(React, 'useReducer').mockImplementation(useReducerMock);

then test it :

   expect(dispatch).toBeCalledWith({
        type: 'MY_ACTION',
        payload: 'Some error message.',
    });

Upvotes: 1

Related Questions