带有 NodeJS 的 Mocha 和 Chai,简单的服务器测试失败并返回 404(应该是 200)

Mocha and Chai with NodeJS, simple server test failing with a 404 (should be 200)

我已经使用 Mocha 和 Chai 编写了一个简单的测试。测试返回为 failed。更改到我正确的测试目录和 运行 npm test 后,返回的错误如下。请有人帮我弄清楚为什么 9000 已被使用?

1) Uncaught error outside test suite
  SERVER TESTS
    2) Should list all of the /gets


  0 passing (43ms)
  2 failing

  1) Uncaught error outside test suite:
     Uncaught Error: listen EADDRINUSE: address already in use :::9000
  2) SERVER TESTS
       Should list all of the /gets:

      Uncaught AssertionError: expected { Object (_events, _eventsCount, ...) } to have status code 200 but got 404
      + expected - actual

      -404
      +200

test.js

// Unit tests for my server using Mocha and Chai

var chai = require("chai");
var chaiHttp = require("chai-http");
var server = require("../hangman-server.js");
var should = chai.should();

chai.use(chaiHttp);


describe("SERVER TESTS", function() {

    it("Should list all of the /gets", function(done) {
        chai.request(server)
        .get("/get")
        .end(function(err, res){
          res.should.have.status(200);
          done();
        });
    });

});

刽子手-server.js

// Creating a listener on the specified port
server.listen(port, async function() {
    // Connect to Mongoose.
    await mongoose.connect(uri, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    });
    console.log("Connected to DB");

    // Output for terminal, 9000 should display in place of the port
    console.log("Listening on " + port);
})

app.get("/", function(request, response) {
    response.status(200).sendFile("/", {root: "client"});
});

我的 package.json 包括 mocha 和 chai

{
  "name": "SOFT355-HangMan",
  "version": "1.0.0",
  "description": "",
  "main": "._hangman-server.js",
  "directories": {
    "test": "test"
  },
  "dependencies": {
    "angular": "^1.7.9",
    "chai": "^4.2.0",
    "chai-http": "^4.3.0",
    "express": "^4.17.1",
    "http": "^0.0.0",
    "mocha": "^6.2.2",
    "mongoose": "^5.7.13",
    "nodemon": "^2.0.2",
    "websocket": "^1.0.30",
    "websocket.io": "^0.2.1"
  },
  "scripts": {
    "test": "mocha",
    "dev": "nodemon hangman-server.js",
    "start": "node hangman-server.js",
    "server": "nodemon hangman-server.js"
  },

Error: listen EADDRINUSE: address already in use :::9000 错误的原因是因为您在一个终端中 运行 npm start,然后在另一个终端中 npm test。因此 npm start 启动一个服务器,而您测试中的 require("../hangman-server.js"); 尝试在同一端口上启动另一个服务器,这会导致此错误消息。

关于 404,您请求 /get,但您的服务器只会响应 /,因为 app.get("/", 将注册中间件以获得 [=17] 的完全匹配=].