【问题标题】:Avoid using localhost to resolve tests in mocha避免使用 localhost 来解决 mocha 中的测试
【发布时间】:2019-02-21 19:40:48
【问题描述】:

由于某种原因,当我像这样在test.js 中设置我的应用程序时:

const app = express();

我收到所有测试的 404 错误。

但是,当我这样设置时

const app = 'http://localhost:3000'

所有测试都通过。

我知道这不是在测试环境中声明app 的最佳方式。如何避免使用像 localhost 这样的修复路径?

示例:

const express = require('express');
const app = express();
// const app = 'http://localhost:3000'
const chai = require("chai");
const expect = chai.expect;
const request = require('supertest');

  it('For all bookings', function (done) {
    request(app)
      .get('/bookings')
      .end(function (err, res) {
        expect('Content-Type', /json/)
        expect(res.statusCode).to.be.equal(200);
        done();
      });
  });

这样我得到Uncaught AssertionError: expected 404 to equal 200

但如果我取消注释 const app = 'http://localhost:3000' 以使用它而不是 const app = express(); 则测试通过。

【问题讨论】:

  • 请添加一些代码示例以帮助重现此错误。谢谢!
  • @lo1c 刚刚做了 :)

标签: node.js express mocha.js chai supertest


【解决方案1】:

const app = express() 创建没有路由的虚拟 Express 实例。它无法响应对/bookings 端点的请求,因为没有这样的端点。

http://localhost:3000 有效意味着具有/bookings 路由的应用程序当前正在运行。

如果应用实例提供给 Supertest 的request,则应导入具有/bookings 路由的应用实例:

const app = require('./app');

【讨论】:

  • 它现在可以工作了,但我得到了Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
  • 同一请求在生产中不会出现错误吗?问题可能是特定于应用程序,而不是 Supertest。该错误通常意味着您发送了两次响应。
【解决方案2】:

如果我们在测试文件中这样做

const app = express();

这意味着我们创建了没有定义路由的全新快递应​​用程序。正确的方法是使用相同的快速应用程序而不是创建一个新应用程序。

为此,我们可以导出 express 应用并从测试文件中引用它。

// index.js
const express = require('express')
const app = express()
const port = 3000

app.get('/bookings', (req, res) => res.send('Hello World!'))

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

module.exports = app; // export express app

同时测试文件

// test.js

...

const app = require("./index"); // import the app

it("For all bookings", function(done) {
  request(app)
    .get("/bookings")
    .end(function(err, res) {
      console.log(res);
      expect("Content-Type", /json/);
      expect(res.statusCode).to.be.equal(200);
      done();
    });
});

希望对你有帮助

【讨论】:

  • 它现在可以工作了,但我得到了Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
  • 您可能需要检查源文件中的代码是否多次发送响应。
猜你喜欢
  • 2016-08-22
  • 1970-01-01
  • 2018-09-04
  • 1970-01-01
  • 2021-04-24
  • 2017-07-22
  • 1970-01-01
  • 2017-12-29
  • 2012-07-15
相关资源
最近更新 更多