我无法检查承诺在Jest测试中是否拒绝错误。
(发布Jest 20版本:)
test("Rejects on error", () => {
expect.assertions(1);
return expect(promiseHttpsGet(null)).rejects.toBeInstanceOf(Error);
});
(前Jest 20版)
test("Rejects on error", () => {
expect.assertions(1);
return promiseHttpsGet(null).catch((err) => {
expect(err).toBeInstanceOf(Error);
});
});
我尝试了两个版本,但Jest测试失败了:
Expected value to be an instance of:
"Error"
Received:
[Error: connect ECONNREFUSED 127.0.0.1:443]
Constructor:
"Error"
承诺返回功能是:
function promiseHttpsGet(url) {
return new Promise((resolve, reject) => {
https
.get(url, (response) => {
let responseBody = "";
if (response.statusCode !== 200) {
reject(response.statusCode);
}
response.setEncoding = "utf8";
response.on("data", (data) => {
responseBody += data;
});
response.on("end", () => {
resolve(responseBody);
});
})
.on("error", (error) => {
reject(error);
});
});
}
任何线索如何解决? 感谢。
答案 0 :(得分:0)
从Jest 23开始,toThrow
匹配器可用于承诺返回功能。
test("Rejects on error", () => {
expect.assertions(1);
return expect(promiseHttpsGet(null)).rejects.toThrow(Error);
});
或async / await版本:
test("Throws on error", async () => {
expect.assertions(1);
await expect(promiseHttpsGet(null)).rejects.toThrow(Error);
});