question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to determine whether req.body was sent as valid JSON

See original GitHub issue

Hi, big fan of msw. But I’m experiencing the following issue:

Describe the bug

I want to return a different response in my resolver depending on whether req.body is valid JSON or not. This is to allow closer imitation of our backend API within our tests.

Previously my test passed despite sending invalid JSON as I always returned a success response, therefore I would like to return an error response from my mock API if the JSON sent is invalid. I believe this is the correct approach as the Request assertions documentation states that we should not be asserting on the body directly and instead include failure scenarios.

I’m currently unable to validate whether the JSON sent is valid as parseBody automatically parses JSON for us or will return the raw object if not parsable, therefore, the following two requests will have the same body in the request resolver.

Valid JSON Request

fetch("/example", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ foo: 'bar' }),
});

Invalid JSON Request

fetch("/example", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: { foo: 'bar' },
});

Resolver

rest.post("/example", (req, res, ctx) => {
  const body = req.body; // Will always be the raw object

  // Shamelessly stolen from https://stackoverflow.com/questions/9804777/how-to-test-if-a-string-is-json-or-not
  function isValidJson(jsonInput) {
    try {
      JSON.parse(jsonInput);
    } catch (e) {
      return false;
    }
    return true;
  }
  
  const bodyWasValid = isValidJSON(req.body); // will always be false

  return res(ctx.json({ bodyWasValid }));
});

In this scenario isValidJSON would always return as false because req.body is always the raw object, I understand returning the raw object is a convenience helper and is a desired behaviour but it makes it impossible to imitate our backend API.

Environment

  • msw: ^0.21.3
  • nodejs: 12.18.3
  • npm: 6.14.8

To Reproduce

Use the above resolver with the above payloads.

Expected behavior

As mentioned above I recognise the automatic parsing of req.body is intentional and would be a breaking change if removed.

My initial thoughts should be that req.body should be ‘[object Object]’ if sent as an object that is not valid JSON. If the body was sent as valid JSON then it should remain as the parsed object.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:16 (11 by maintainers)

github_iconTop GitHub Comments

1reaction
kettanaitocommented, Feb 18, 2021

The fix on the whatwg-fetch side has been published: https://github.com/github/fetch/releases/tag/v3.6.0. I suggest updating that dependency and checking if the issue is gone.

1reaction
kettanaitocommented, Feb 13, 2021

I see little value in keeping this issue open: there is nothing to be addressed on the MSW side. The issue is in the whatwg-fetch polyfill as it handles a non-stringified JSON body differently than window.fetch in a browser (see #856). As the status of that polyfill is “not maintained”, I can suggest you switching to a different polyfill in your tests.

You can still track the resolution progress with whatwg-fetch in this pull request: https://github.com/github/fetch/pull/881.

Read more comments on GitHub >

github_iconTop Results From Across the Web

fastapi - How to read body as any valid json? - Stack Overflow
In the edit history of this answer it seems that request.body() has been replaced by request.json() only inside the code block :-) –...
Read more >
5.x API - Express.js
A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body ), or an empty...
Read more >
JSON to XML policy runtime error troubleshooting | Apigee Edge
In the failed JSON to XML policy XML, verify that the name of the variable set in the <Source> element matches the variable...
Read more >
How to Validate JSON Request Body in Spring Boot - SmattMe
Because RequestValidator.validate() expects Object data type, the request object can be a Map, a POJO or even a JSON String. If an API...
Read more >
How to handle request validation in your Express API
First things first, parse that JSON request body ... nice to be able to use middleware to validate request data which has been...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found