【发布时间】:2022-01-13 20:55:03
【问题描述】:
问题
我正在测试 API 端点,并且对每个端点都有一些相同的测试。我不想复制和粘贴,而是想在可重用的功能中分享它。我还希望为每个函数将一条语句打印到控制台(通过test),所以我不想结合逻辑。
代码
这是应该共享的功能:
export function basicTests(res) {
test("should respond with a 200 status code", () => {
expect(res.statusCode).toBe(200);
});
test("should specify json in the content type header", () => {
expect(res.headers["content-type"]).toEqual(expect.stringContaining("json"));
});
test("should return an ok property", () => {
expect(res.body.ok).toBeDefined();
});
test("should return a description property", () => {
expect(res.body.description).toBeDefined();
});
}
这是我在另一个文件中调用测试的方式:
let res = {}
beforeAll(async () => {
const response = await request(app)
.get("/some/api/check")
.send();
res = { ...response };
});
describe("GET /some/api/route", () => {
basicTests(res);
// ... more tests
});
什么不起作用
目前当我传入res 时,它始终是一个空对象。因此,即使 beforeAll 在测试之前运行,变量似乎也更早通过,因此在 Promise 解决时不会更新。
我该如何解决这个问题?
【问题讨论】:
标签: javascript node.js ecmascript-6 jestjs supertest