Kri*_*all 2 javascript api json typescript jestjs
我正在为API编写单元测试。
如果我做这样的事情:
const apiResponse:object = JSON.parse(body)
expect(apiResponse).toHaveProperty('error')
Run Code Online (Sandbox Code Playgroud)
而且API没有返回JSON,那么我得到了类似的信息:
SyntaxError:JSON中的意外令牌p在JSON.parse()的位置0
我希望测试不会失败,而不是在测试中出错。
我可以说这是什么玩笑测试?
我收到的此字符串可解析为有效JSON吗?
我通过添加我在这里找到的辅助函数解决了这个问题
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
}
Run Code Online (Sandbox Code Playgroud)
然后能够做到这一点:
expect(isJSON(body)).toBe(true)
Run Code Online (Sandbox Code Playgroud)
您可以简单地使用Jest.not.toThrow()来断言 JSON 解析不会引发错误。
这是我制作的一个示例,它断言一个对象可以被解析为有效的 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();
});
Run Code Online (Sandbox Code Playgroud)
例如,如果对象具有圆形结构:
var obj = {
a: "foo",
b: obj
}
Run Code Online (Sandbox Code Playgroud)
测试将失败:
Expected the function not to throw an error.
Instead, it threw:
TypeError: Converting circular structure to JSON
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2010 次 |
| 最近记录: |