简体   繁体   English

使用我的Node.js REST API设置Mocha / ChaiHttp单元测试时遇到问题

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

I am trying to set up unit testing for my node.js REST API using mocha and chaihttp, but my sample test which should pass seems to be failing. 我正在尝试使用mocha和chaihttp为我的node.js REST API设置单元测试,但是应该通过的示例测试似乎失败了。

My code for the unit tests is here: 我的单元测试代码在这里:

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();
            });
    });
});

And the error I get when running the tests: 我在运行测试时得到的错误:

  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)

From what it looks like, it's unable to connect to my local host or something because I'm getting a 404 error whereas if I manually go to localhost:3000 in my browser, I'm served a simple Hello world index page. 从外观上看,它无法连接到本地主机或其他东西,因为出现了404错误,而如果我在浏览器中手动转到localhost:3000,则可以访问一个简单的Hello world索引页面。

Here is my index.js route if it might be relevant: 如果可能的话,这是我的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;

A minor adjustment to make would be to make sure your request is against the base URL and not the base URL with a slash on the end. 要做的一个小调整是确保您的请求是针对基本URL的,而不是针对末尾带有斜杠的基本URL。 The chai-http docs have examples like this: chai-http文档具有以下示例:

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

The code posted here has: 此处发布的代码具有:

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

Try and adjust it to be: 尝试将其调整为:

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

For debugging, you could also try and add a few other endpoints and see if they work instead. 对于调试,您还可以尝试添加其他一些端点,然后查看它们是否起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM