【问题标题】:supertest not found error testing express endpointsupertest not found 错误测试快速端点
【发布时间】:2019-10-01 00:42:56
【问题描述】:

我尝试设置 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!”

【问题讨论】:

  • 问题在于测试文件中的新应用实例。您应该从 index.js 导出应用程序实例并在 index.test.js 中使用它,或者将测试与 index.js 中的代码一起编写,这不是生产代码的首选。
  • 我现在收到这个错误`listen EADDRINUSE: address already in use :::3000`
  • 不要使用node index.js 或类似的方式启动服务器。 Supertest 会运行它。 “您可以将 http.Server 或函数传递给 request() - 如果服务器尚未侦听连接,则它会为您绑定到临时端口,因此无需跟踪端口。”跨度>
  • 请参阅tutorial,它将详细解释步骤。我快速浏览了一下,但没有阅读全文。

标签: javascript node.js express jestjs supertest


【解决方案1】:

你应该重构 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);
      });
  });
});

【讨论】:

  • app.js 末尾还需要module.exports = app;
【解决方案2】:

这是因为您的测试中的 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("/")
...

【讨论】:

  • 测试时,不要运行主服务器
  • 等等,如果我不运行主服务器,测试将如何获得响应?
  • supertest 会为你运行它
猜你喜欢
  • 2020-02-15
  • 2019-06-09
  • 2014-06-18
  • 1970-01-01
  • 1970-01-01
  • 2021-01-12
  • 1970-01-01
  • 1970-01-01
  • 2020-08-21
相关资源
最近更新 更多