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', () => {
jest.mock('api', () => ({
actionCreators: {
confirmOrder: jest.fn()
},
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 ();
} }
/>
</>
);
};
I'd like to get some advice on how I can possibly test via Jest that the dispatch function inside handleConfirmOrder was called. Thanks in advance.