supertest 未找到错误测试 express 端点

supertest not found error testing express endpoint

我尝试设置 jest、supertest 和 express 但失败了。我有这两个简单的文件

index.js

const express = require("express");
const app = express();
const port = 3000;

app.get("/", (req, res) => res.send("Hello World!"));

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

和index.test.js

const express = require("express");
const app = express();
const request = require("supertest");

describe("/", () => {
  test("it says hello world", done => {
    request(app)
      .get("/")
      .expect(200)
      .end(function(err, res) {
        console.log("err", err);
      });
  });
});

当我 运行 测试时,我遇到了这个错误。 err Error: expected 200 "OK", got 404 "Not Found"

怎么了?

我在浏览器中访问 localhost:3000 我可以看到 'Hello World!'

这是因为您测试中的 app 实例与您 index.js

中的 运行 实例不同

从您的 index.js 中导出应用:

const server = app.listen(port, () => console.log(`Example app listening on port ${port}!`));
module.exports = server;

并在您的测试中导入:

const server = require('./index.js');

// pass your server to test
...
request(server)
  .get("/")
...

您应该重构 index.js 并创建 app.js

app.js

const express = require("express");
const app = express();
app.get("/", (req, res) => res.send("Hello World!"));

index.js

const app = require('./app')
const port = process.env.PORT
app.listen(port, () => { console.log(`listening on ${port}) . })

我们这样重构代码的原因是我们需要访问 express app() 但我们不希望 "listen" 被调用。

in your test file

const request = require("supertest");
const app = require("../src/app");

describe("/", () => {
  test("it says hello world", done => {
    request(app)
      .get("/")
      .expect(200)
      .end(function(err, res) {
        console.log("err", err);
      });
  });
});