Configuring request handlers for API endpoints
In this section, we will define handlers for our application. As already mentioned, a handler in MSW is a function that, if defined, will intercept any matching requests, and instead of sending the requests to the network, it will modify them and return the mocked response.
API utils
Before getting started, let’s take a quick look at the src/testing/mocks/utils.ts
file, which includes some utilities we will be using for handling the business logic of our API handlers:
authenticate
accepts user credentials, and if they are valid, it will return the user from the database together with the authentication token.getUser
returns a test user object.requireAuth
returns the current user if the token in the cookie is available. It can optionally throw an error if the token does not exist.
Before getting started, let’s include all handlers in the configuration. Open the src/testing/mocks/handlers/index...