I'm writing unit tests for an API.
If I do something like this :
const apiResponse:object = JSON.parse(body)
expect(apiResponse).toHaveProperty('error')
and the API is not returning JSON, then I get something like :
SyntaxError: Unexpected token p in JSON at position 0 at JSON.parse ()
Rather than getting an error in my tests, I'd like my test to fail.
What is a jest test I can do that says;
is this string I've received parsable as valid JSON?
I solved this by adding a helper function I found here
const isJSON = (str:string) => {
try {
const json = JSON.parse(str);
if (Object.prototype.toString.call(json).slice(8,-1) !== 'Object') {
return false
}
} catch (e) {
return false
}
return true
}
and then am able to do this :
expect(isJSON(body)).toBe(true)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With