Mocks
Loading "Mocking Apis with Msw and Testing"
Run locally for transcripts
Mocking API calls is important not only for testing (which is where it's more
often associated), but also during development. It makes you faster at releasing
features because it allows you to work in parallel with the team responsible
for the API you're calling and it also helps you avoid issues with keeping
private keys locally and if the service ever falls over you can continue to
develop.
The de-facto standard for mocking API calls in Node.js applications is
MSW. MSW is a library that can run in both the browser and
on the server and allows you to intercept any request made by your application.
It gives you the opportunity to either let the request go through to the
original endpoint or to return a mocked response.
Here's a simple example of setting up a mock for an API call (modified) from
their docs:
import { http, HttpResponse } from 'msw'
import { setupServer } from 'msw/node'
const server = setupServer(
// Describe the requests to mock.
http.get(
'https://example.com/book/:bookId',
({ request, params, cookies }) => {
return HttpResponse.json({
title: 'Lord of the Rings',
author: 'J. R. R. Tolkien',
})
},
),
http.post('/users/:userId', async ({ request, params, cookies }) => {
const { userId } = params
const data = await request.json()
// do something with the data
return HttpResponse.json({
id: userId,
firstName: 'John',
lastName: 'Maverick',
})
}),
)
server.listen({ onUnhandledRequest: 'warn' })
With this set up and running within your server, any request made to a URL
matching those patterns will be intercepted by MSW and return a mocked response
instead.
π§ββοΈ Like I said, I already got some things set up for you, so you'll just need to
add a mock for the resend email API call. You'll also need to be the one who
gets the mocks file imported and sets the right environment variable during
development to enable that.
π¨βπΌ I recommend you start in the file
to add the mock, and then set the
MOCKS
environment variable
in , and then finally import the mocks
file in .