admin管理员组文章数量:1222506
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'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?
- 2 Wrap it in a try/catch. There's no built in way of testing for json validity other than parsing it. – Adrian Commented Mar 27, 2018 at 9:01
- Expanding on @Adriani6 Change your code to wrap the parse in a Try/Catch, then return an exception when the parse fails, and then Jest can test for the exception with bad JSON, and another normal test for good JSON data. – Steven Scott Commented Mar 27, 2018 at 14:21
2 Answers
Reset to default 9I 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)
You can simply use Jest's .not.toThrow()
to assert that the JSON parsing doesn't throw an error.
Here is an example I made that asserts an object can be parsed to valid JSON:
it("Produces metadata object that can be parsed to valid JSON", () => {
const meta = articleMetaData(article);
const parseJson = () => {
const json = JSON.stringify(meta);
JSON.parse(json);
};
expect(parseJson).not.toThrow();
});
If, for example, the object had a circular structure:
var obj = {
a: "foo",
b: obj
}
The test would fail:
Expected the function not to throw an error.
Instead, it threw:
TypeError: Converting circular structure to JSON
本文标签: javascriptjesthow to test JSONparse on a string will succeedStack Overflow
版权声明:本文标题:javascript - jest ; how to test JSON.parse on a string will succeed - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739386083a2160939.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论