CodePark/ questions / Hooks, context & providers
START PRACTICINGPRACTICE
Frontend question · Testing › Hooks, context & providers

useCart() throws 'useCart must be used within CartProvider'. How do you test the hook?

renderHook(() => useCart(), { wrapper: CartProvider })

renderHook(() => useCart(), { wrapper: CartProvider }) is right. The wrapper option renders the provider around the hook, just as in the app. Calling useCart() directly in the test body is wrong. Hooks can't run outside a component, so that breaks the rules of hooks. The @testing-library/react-hooks option is wrong because that package is deprecated. Mocking useContext is wrong because it tests a fake instead of the real provider.