mswjs / http-middleware

Spawn an HTTP server from your request handlers or apply them to an existing server using a middleware.
https://npm.im/@mswjs/http-middleware
107 stars 13 forks source link

Doesn't work when used with "express.json" middleware #18

Closed nnnnat closed 2 years ago

nnnnat commented 2 years ago

Hey y'all big fan of MSW!

I've been using MSW & http-middleware together to create a mock GraphQL API for a few months & I've recently run into an issue after updating to MSW v0.44.2 & http-middleware v0.5.0. I have a very similar setup to the custom server example in this repo & after updating all GQL operations now seem to pass through & return a 404 "Mock not found".

I've put together a small example that reproduces the issue I'm seeing.

kettanaito commented 2 years ago

Hey, @nnnnat. Thanks for raising this.

I've taken a quick look and it seems that the body we encode in the middleware results in the encoded "[object Object]" string. When MSW attempts to parse that body, it treats it as a string, so it doesn't pass as a valid GraphQL API request.

I believe the issue is somewhere around here:

https://github.com/mswjs/http-middleware/blob/ca849760dd3e32e990d33d66d393c101e5dc1f02/src/middleware.ts#L22

If I look at your server, I can see that you use express.json() middleware. It will preserve the JSON request body as an object, and that causes the issue:

https://github.com/nnnnat/msw-middleware-example/blob/22c1a8d1c6f1b600ae14562559ad5c25a9ffe61f/main.js#L8

On the middleware's side, we need to check if the req.body is an object and stringify it in that case, so that encodeBuffer always accepts a plain string.

kettanaito commented 2 years ago

Released: v0.5.1 🎉

This has been released in v0.5.1!

Make sure to always update to the latest version (npm i @mswjs/http-middleware@latest) to get the newest features and bug fixes.


Predictable release automation by @ossjs/release.