首页 > 解决方案 > 如何使用 AVA 测试 Express.js 应用程序?

问题描述

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

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

标签: expresstestingava

解决方案


在玩了一些并参考了supertest repo之后,我能够得到以下工作:

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

推荐阅读