如何使用 AVA 测试 Express.js 应用程序?



我可以用AVA测试我的模型,但我也想测试路线。

我觉得应该可以访问 Express 应用程序对象,并向其传递一个 URL,然后查看返回的内容,但我不知道如何让 Express 对象使用它。

经过一些尝试并引用超级测试存储库,我能够获得以下工作:

const test = require("ava");
const request = require("supertest");
const express = require("express");
test("test express handler with supertest", async t => {
// in async tests, it's useful to declare the number of
// assertions this test contains
t.plan(3);

// define (or import) your express app here
const app = express();
app.get("/", (req, res) => {
res.json({
message: "Hello, World!",
});
});

// make a request with supertest
const res = await request(app).get("/").send();

// make assertions on the response
t.is(res.ok, true);
t.is(res.type, "application/json");
t.like(res.body, {
message: "Hello, World!",
});
});

我倾向于使用以下 shell 命令运行 AVA:

yarn ava --verbose --watch

最新更新