axios-mock-adapter icon indicating copy to clipboard operation
axios-mock-adapter copied to clipboard

isBodyMatching fails for string args if first arg is parsable JSON

Open joebowbeer opened this issue 5 years ago • 0 comments

I want to match against an expected string body (requiredBody) rather than a JSON object because I want to verify that my transformData functions are working as intended. Matching against a string should be more representative of what the adapter sees in real life.

However, as you can see in the isBodyMatching source below, this will fail, because the actual string body will be parsed before it is compared to my requiredBody string.

Fix: The parsing below should not be performed if requiredBody is a string.

function isBodyMatching(body, requiredBody) {
  if (requiredBody === undefined) {
    return true;
  }
  var parsedBody;
  try {
    parsedBody = JSON.parse(body);
  } catch (e) {}

  return isObjectMatching(parsedBody ? parsedBody : body, requiredBody);
}

As a workaround, I implemented the comparison in a function(config) passed to reply.

Another workaround might be to use a RequestDataMatcher with an asymmetricMatch.

joebowbeer avatar May 24 '20 06:05 joebowbeer