Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jest ; how to test JSON.parse on a string will succeed

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?

like image 874
Kris Randall Avatar asked Mar 27 '18 08:03

Kris Randall


1 Answers

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)
like image 195
Kris Randall Avatar answered Oct 01 '22 16:10

Kris Randall