Mocking Arbitrary Imports: Continued
Explore how to mock HTTP requests in Jest using the jest-fetch-mock library. Learn to write unit tests for API helper functions like getTasks and updateTask, verify fetch call arguments with regex matching, and implement functions based on test behavior. This lesson builds skills for effective module mocking in React testing scenarios.
We'll cover the following...
Where we left off
In the last lesson, we introduced a new persistence feature to our app, and wrote an integration test for it. The test boils down to:
- Create a task.
- Refresh the page.
- Make sure the task is there.
- Mark task as completed.
- Refresh the page.
- Make sure it stays completed.
Next, we will write unit tests that validate each step of that scenario.
API functions
Since we have set up json-server, our trusty backend, we will need to interface with it. I suggest that we first test and create helper functions to make API requests. We will put them in /api/index.js. That means their tests will be under /api/index.test.js. Go ahead and create this file, but leave it empty for now.
Let us take a ...