在下面的代码块(示例 #1)中,expect(this.req.headers["user-agent"]).to.equal("BOOM")
抛出错误并且测试失败。
describe("http.get with headers", () => {
it("should return response with status code 200", async () => {
const userAgent =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:74.0) Gecko/20100101 Firefox/74.0"
nock("https://api.example.net")
.get("/hello")
.reply(function() {
expect(this.req.headers["user-agent"]).to.equal("BOOM")
return [200]
})
const httpInstance = new http({
headers: {
"user-agent": userAgent,
},
})
let response = await httpInstance.get("https://api.example.net/hello")
expect(response.statusCode).to.equal(200)
})
})
在以下代码块(示例 #2)中,expect(requestBody.message).to.equal("BOOM")
抛出“静默”错误(return [200]
从不执行),但测试通过。为什么?
describe("logger.captureMessage(message, callback)", () => {
it("should send captured exception to sentry", () => {
return new Promise((resolve, reject) => {
nock("https://sentry.io")
.post("/api/3926156/store/")
.reply((uri, requestBody: any) => {
expect(requestBody.message).to.equal("BOOM")
return [200]
})
logger.captureMessage("foo", () => {
resolve()
})
})
})
})
使用catch
和触发reject
是可行的,但是当示例 #1 中一切正常时,为什么有必要这样做呢?
describe("logger.captureMessage(message, callback)", () => {
it("should send captured exception to sentry", () => {
return new Promise((resolve, reject) => {
nock("https://sentry.io")
.post("/api/3926156/store/")
.reply((uri, requestBody: any) => {
try {
expect(requestBody.message).to.equal("BOOM")
return [200]
} catch (error) {
reject(error)
}
})
logger.captureMessage("foo", () => {
resolve()
})
})
})
})