我正在和一位同事争论 done()
在 Jest 测试中。
他在 JavaScript 方面的经验比我多几个数量级,我在 async
之后加入。/await
被普遍接受,加上来自.NET环境,所以习惯了。
我这样写我的测试:
it("should return 200 OK for POST method", async () => {
await request(app).post("SOMEENDPOINT")
.attach("file", "file")
.expect(200);
});
他更习惯于 promise ,所以会这样写他的测试:it("should return 200 OK for POST method", (done) => {
request(app).post("SOMEENDPOINT")
.attach("file", "file")
.expect(200, done);
});
他对我推到 async
没意见/await
,但坚持我必须包括 done
,这样我要么做他的版本修改版本:it("should return 200 OK for POST method", async (done) => {
await request(app).post("SOMEENDPOINT")
.attach("file", "file")
.expect(200, done);
});
或者:it("should return 200 OK for POST method", async (done) => {
const res = await request(app).post("SOMEENDPOINT")
.attach("file", "file");
expect(res.status).toBe(200);
done();
});
虽然我知道调用 done()
当它作为参数包含时是完全必要的,我的印象是使用 async
时完全没有必要/await
在这种情况下。请求是
supertest.request
.我的问题是,我需要使用
done
完全没有async
/await
?
最佳答案
永远不需要done
和 async
在同一个测试函数上。选择其中一个,或者,在这种情况下,直接返回 promise :
it("should return 200 OK for POST method", () =>
request(app).post("SOMEENDPOINT")
.attach("file", "file")
.expect(200)
);
开 Jest 会await
任何返回的 promise ,这意味着我们总是可以手动构造并返回没有 async
的 promise 或 done
.这是多余的,因为我们手头已经有了一个 promise ,但是下面的 pattern是可能的,如果仅用于说明目的:it("should return 200 OK for POST method", () => {
return new Promise((resolve, reject) => {
request(app).post("SOMEENDPOINT")
.attach("file", "file")
.expect(200, resolve)
.catch(err => reject(err))
;
});
});
done
通常用于测试异步回调(想想 fs
模块中的基本 Node 库实用程序)。在这些情况下,添加 done
会更优雅。参数并在回调中调用它,而不是手动 promise 回调。本质上,done
是抽象出 new Promise
的 promise 的捷径样板如上所示。请注意
done
可以接受被视为错误的参数(参见 docs )。这应该进入任何 catch
block 以避免在调用 done
之前引发主行代码时出现超时和混淆错误:it("should return 200 OK for POST method", done => {
request(app).post("SOMEENDPOINT")
.attach("file", "file")
.expect(200, done)
.catch(err => done(err))
;
});
关于javascript - 在异步 Jest 测试中是否需要完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58713379/