Testing if dispatch was called inside function of a custom hook

Viewed 47

I have a custom hook written like so:

export default function useOrder(orderInfo) {

  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (confirmOrderFailed) {
      setLoading(false);
    }
  }, [confirmOrderFailed, setLoading]);

  const handleConfirmOrder = () => {
    dispatch(
      api.actionCreators.confirmOrder(
        {},
        {
          body: {
            order,
            orderId
          }
        }
      )
    );
    setLoading(true);
  };

  return {
    handleConfirmOrder,
    confirmOrderFailed,
    loading
  };
}

I'm trying to write a unit test to check that the dispatch function above was called. So far I have written this:

  it('should call dispatch inside handleConfirmOrder', () => {

    const orderDetails = {
      handleConfirmOrder: jest.fn(),
      confirmOrderFailed: false,
      loading: false,
    };

    jest.spyOn(hooks, 'useOrder').mockImplementation(() => orderDetails );

    jest.mock('api', () => ({
      actionCreators: {
        confirmOrder: jest.spyOn(orderDetails, 'handleConfirmOrder').mockReturnValue({})
      },
      selectors: {
        confirmOrder: jest.fn().mockReturnValue({
          isLoaded: true,
          hasError: false,
          value: { checkoutUrl }
        })
      }
    }));

    renderWithRedux(<TestComponent />, {
      initialConfigState,
      initialReduxState
    });

    userEvent.click(screen.getByRole('button'));
    expect(api.actionCreators.confirmOrder).toBeCalledWith(
      {},
      { 
         body: { order, orderId } 
      }
    );
  });

However, I get an error saying:

expect(received).toBeCalledWith(...expected)

    Matcher error: received value must be a mock or spy function       

    Received has type:  function
    Received has value: [Function anonymous]

      154 |     });
      155 |     userEvent.click(screen.getByRole('button'));
    > 156 |     expect(api.actionCreators.confirmOrder).toBeCalledWith(   
          |                                          ^
      157 |       {},
      158 |       { body: { order, orderId } }
      159 |     );

Here is the <TestComponent/> if needed:

  const TestComponent = () => {
    const {
      loading,
      confirmOrderFailed,
      handleConfirmOrder 
    } = useOrder(order);

    return (
      <>
        <p>{ `loading: ${loading}` }</p>
        <p>{ `confirmOrderFailed: ${confirmOrderFailed}` }</p>
        <button
          onClick={ () => {
            handleConfirmOrder ();
          } }
        />
      </>
    );
  };

How can I test via Jest that the dispatch function inside handleConfirmOrder was called?

0 Answers
Related