【问题标题】:How do I test an Express.js app with AVA?如何使用 AVA 测试 Express.js 应用程序?
【发布时间】:2020-04-20 03:35:00
【问题描述】:

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

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

【问题讨论】:

  • 请提供您要测试的路线。此外,您想要哪种测试,单元测试还是集成测试?

标签: express testing ava


【解决方案1】:

经过一番玩弄并引用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

【讨论】:

    猜你喜欢
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 2012-01-16
    相关资源
    最近更新 更多