Chai 和 Mocha:测试停止 express 服务器监听

Chai & Mocha: Tests stop express server from listening

我使用 chai 编写了测试。这里只是三个示例测试:

(实际测试较多,请查看repl链接)

文件:tests/2_functional-tests.js

const chaiHttp = require('chai-http');
const chai = require('chai');
const assert = chai.assert;
const app = require('../app');

chai.use(chaiHttp);
const request = chai.request;

let id1;
let id2;

suite('Functional Tests', function() {
  test("Create an issue with every field: POST request to /api/issues/{project}", async () => {
    const res = await request(app)
    .post("/api/issues/testproject")
    .set('content-type', 'application/x-www-form-urlencoded')
    .send({
      issue_title: "Test issue",
      issue_text: "Test issue text",
      created_by: "Chai func test nr 1",
      assigned_to: "nobody :P",
      status_text: "didn't even start"
    });
    assert.equal(res.status, 200);
    let responseObj = JSON.parse(res.res.text);
    assert.equal(responseObj.issue_title, "Test issue");
    assert.equal(responseObj.issue_text, "Test issue text");
    assert.equal(responseObj.created_by, "Chai func test nr 1");
    assert.equal(responseObj.assigned_to, "nobody :P");
    assert.equal(responseObj.status_text, "didn't even start");
    assert.isTrue(responseObj.open);

        id1 = responseObj._id;     
  });

  test("Create an issue with missing required fields: POST request to /api/issues/{project}", async () => {
    const res = await request(app)
      .post("/api/issues/testproject")
      .set('content-type', 'application/x-www-form-urlencoded')
      .send({
        issue_title: "Test issue 3", //no issue_text
        created_by: "Chai func test nr 3"
      });
    assert.equal(res.status, 200);
    let responseObj = JSON.parse(res.res.text);
    assert.equal(responseObj.error, "required field(s) missing")
  });

  test("View issues on a project with multiple filters: GET request to /api/issues/{project}", async () => {
    const res = await request(app)
      .get("/api/issues/testproject?open=true&created_by=Chai+func+test+nr+1")

    assert.equal(res.status, 200);
    let responseObj = JSON.parse(res.res.text);

    assert.equal(responseObj.length, 1);
    assert.equal(responseObj[0].issue_text, "Test issue text");
    assert.equal(responseObj[0].status_text, "didn't even start");
    assert.equal(responseObj[0].created_by, "Chai func test nr 1");
    assert.equal(responseObj[0].open, true);
  });
});

这些测试都按预期工作。我 没有 得到任何错误。尽管如此,这些测试阻止了我的快速服务器监听。

这里我在听然后开始测试运行ner: (在 server.js 文件中)

const listener = app.listen(process.env.PORT || 3000, function () {
  console.log('Your app is listening on port ' + listener.address().port);
  if (process.env.NODE_ENV === 'test') {
    console.log('Running Tests...');
    setTimeout(function () {
      try {
        runner.run();
      } catch (e) {
        console.log('Tests are not valid:');
        console.error(e);
      }
    }, 5000);
  }
});

当我启动服务器时,它会侦听并且所有路由都可用。但是,测试 运行ner 启动后,服务器停止侦听并且路由停止工作。但有趣的是,如果我删除测试和 运行 只是空套件,就像这样:

const chaiHttp = require('chai-http');
const chai = require('chai');
const assert = chai.assert;
const app = require('../app');

chai.use(chaiHttp);
const request = chai.request;

let id1;
let id2;

suite('Functional Tests', function() {
});

...一切正常,服务器一直在监听。

runner.runtest-runner.js 文件中 emitter.run 函数。

const analyser = require('./assertion-analyser');
const EventEmitter = require('events').EventEmitter;

const Mocha = require('mocha'),
    fs = require('fs'),
    path = require('path');

const mocha = new Mocha();
let testDir = './tests'


// Add each .js file to the mocha instance
fs.readdirSync(testDir).filter(function(file){
    // Only keep the .js files
    return file.substr(-3) === '.js';

}).forEach(function(file){
    mocha.addFile(
        path.join(testDir, file)
    );
});

let emitter = new EventEmitter();
emitter.run = function() {

  let tests = [];
  let context = "";
  let separator = ' -> ';
  // Run the tests.
  try {
  let runner = mocha.ui('tdd').run()
    .on('test end', function(test) {
        // remove comments
        let body = test.body.replace(/\/\/.*\n|\/\*.*\*\//g, '');
        // collapse spaces
        body = body.replace(/\s+/g,' ');
        let obj = {
          title: test.title,
          context: context.slice(0, -separator.length),
          state: test.state,
          // body: body,
          assertions: analyser(body)
        };
        tests.push(obj);
    })
    .on('end', function() {
        emitter.report = tests;
        emitter.emit('done', tests)
    })
    .on('suite', function(s) {
      context += (s.title + separator);

    })
    .on('suite end', function(s) {
      context = context.slice(0, -(s.title.length + separator.length))
    })
  } catch(e) {
    throw(e);
  }
};

module.exports = emitter;

This is a project of the freecodecamp.org curriculum,而test-runner.js只是starter项目的,所以我没有接触它,我认为它没有任何问题。

可能是什么问题?难不成是代码结构有严重问题?

Here is a link to the project on replit - Feel free to fork

- 测试前:

- 测试后:

看起来这是 replit 的问题,如果我在本地下载文件和 运行 服务器,一切都会无缝运行。

这些测试对于 replit 免费层服务器来说可能太难处理了。 但是如果我等待(5-10 分钟),服务器将再次开始监听。

不幸的是,我对问题中的 link 进行了一些编辑,因此您现在可能无法重现该错误。 (这些编辑以某种方式大大减少了等待时间)

但是here is an older version of the project,还是有错误,只是结构不同而已。以防万一有人想看一看。