Design Patterns · Middle · Question 18 of 75
How do you inject a dependency into React components so you can swap the API client in tests?
- ✓Correct answer: Pass the client via a Context provider and wrap with a different value in tests
- 2Import the client directly and change a global variable in tests
- 3Create a new client inside every component during render
Explanation
Context is React's built-in DI mechanism: <ApiProvider client={mockClient}> in tests and Storybook, the real client in the app. QueryClientProvider and the Redux store provider work the same way.