无法使用我的 Node.js REST API 设置 Mocha/ChaiHttp 单元测试

Trouble Setting Up Mocha/ChaiHttp Unit Tests With My Node.js REST API

我正在尝试使用 mocha 和 chaihttp 为我的 node.js REST API 设置单元测试,但我应该通过的示例测试似乎失败了。

我的单元测试代码在这里:

var express = require('express');
var router = express.Router();

var chai = require("chai");
var chaiHttp = require('chai-http');
chai.use(chaiHttp);

describe("Test", function() {
    it('Simple test', function(done) {
        chai.request('http://localhost:3000/')
            .get('/')
            .end(function(err, res) {
                chai.expect(res).to.have.status(200);
                done();
            });
    });
});

我在 运行 测试时得到的错误:

  1) Test Simple test:
     Uncaught AssertionError: expected { Object (domain, _events, ...) } to have status code 200 but got 404
      at tests.js:13:42
      at Test.Request.callback (/Users/laptop/Desktop/Toptal/node_modules/superagent/lib/node/index.js:631:3)
      at IncomingMessage.<anonymous> (/Users/laptop/Desktop/Toptal/node_modules/superagent/lib/node/index.js:795:18)
      at endReadableNT (_stream_readable.js:974:12)
      at _combinedTickCallback (internal/process/next_tick.js:74:11)
      at process._tickCallback (internal/process/next_tick.js:98:9)

看起来,它无法连接到我的本地主机或其他东西,因为我收到 404 错误,而如果我在浏览器中手动转到 localhost:3000,我会得到一个简单的你好世界索引页。

这是我的 index.js 路线,如果它可能相关的话:

var express = require('express');

var router = express.Router();

router.get('/', function(req, res, next) {
    res.status(200).render('index.ejs');
});

module.exports = router;

需要做的一个小调整是确保您的请求是针对基数 URL 而不是末尾带有斜线的基数 URL。 chai-http 文档有这样的示例:

chai.request('http://localhost:8080')
  .get('/')

此处发布的代码有:

chai.request('http://localhost:3000/') /* Includes the resource `/` */
            .get('/')

尝试调整为:

chai.request('http://localhost:3000') /* Just the base URL */
            .get('/')

对于调试,您还可以尝试添加一些其他端点,看看它们是否有效。