TIL MSW for mocking
POSTED ON:
Via How I built a modern website in 2021
MSW #
I learned about MSW: https://mswjs.io/
MSW is a API mocking tool. Mock by intercepting requests on the network level. Seamlessly reuse the same mock definition for testing, development, and debugging.
import { setupWorker, rest } from 'msw'
const worker = setupWorker(
rest.post('/login', async (req, res, ctx) => {
const { username } = await req.json()
return res(
ctx.json({
username,
firstName: 'John'
})
)
}),
)
worker.start()
How does Kent use MSW in his website? #
MSW is a fantastic tool for mocking network requests in both the browser and node. For me, 100% of my 3rd party network requests happen in Remix loaders on the server, so I only have MSW setup in my node server. What I love about MSW is that it's completely nonintrusive on my codebase. The way I get it running is pretty simple. Here's how I start my server:
For several of the APIs I have mocked, I'm just using faker.js to create random fake data that conforms to the types I've written for these APIs.
But for the GitHub APIs, I actually happen to know what the response should be even if I'm not connected to the internet, because I'm literally working in the repository that I'll be requesting content from! So my GitHub API mock actually reads the filesystem and responds with actual content.
A image optimization strategy #
Another cool thing I'm doing that you may have noticed on the blog posts is on the server I make a request for the banner image that's only 100px wide with a blur transform. Then I convert that into a base64 string. This is cached along with the other metadata about the post. Then when I server-render the post, I server-render the base64 blurred image scaled up (I also use backdrop-filter with CSS to smooth it out a bit from the upscale) and then fade-in the full-size image when it's finished loading. I'm pretty darn happy with this approach.
I'm a big fan of converting small images into base64 string!
Related TILs
Tagged: testing