首页 > 解决方案 > 使用快递服务器时,摩卡在超测后没有停止

问题描述

我有一个像这样使用 mocha 的简单超测测试。

describe("test", () =>{
  it("Test 1", (done) =>{
    let app = (new App()).express;
    supertest(app).get("/").expect(200, done);
  })
})

测试运行并通过,但从未关闭 mocha。我试过这个。

describe("test", () =>{
  it("Test 1", (done) =>{
    let app = (new App()).express;
    supertest(app).get("/").expect(200, ()=>{
      app.close();
      done();
    });
  })
})

但是app.close没有声明,我也没有卷起整个服务器。测试后如何让摩卡咖啡停止?

标签: mocha.jssupertest

解决方案


这是一个最小的工作示例:

app.js

const express = require("express");
const app = express();

app.get("/", (req, res) => {
  res.sendStatus(200);
});

const port = 3000;
const server = app.listen(port, () => {
  console.info(`HTTP server is listening on http://localhost:${port}`);
});

module.exports = server;

app.test.js

const app = require("./app");
const supertest = require("supertest");

describe("test", () => {
  after((done) => {
    app.close(done);
  });

  it("Test 1", (done) => {
    supertest(app)
      .get("/")
      .expect(200, done);
  });
});

带有覆盖率报告的集成测试结果:

HTTP server is listening on http://localhost:3000
  test
    ✓ Test 1


  1 passing (23ms)

-------------|----------|----------|----------|----------|-------------------|
File         |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files    |      100 |      100 |      100 |      100 |                   |
 app.js      |      100 |      100 |      100 |      100 |                   |
 app.test.js |      100 |      100 |      100 |      100 |                   |
-------------|----------|----------|----------|----------|-------------------|

启动 HTTP 服务器:

☁  mocha-chai-sinon-codelab [master] ⚡  node /Users/ldu020/workspace/github.com/mrdulin/mocha-chai-sinon-codelab/src/stackoverflow/53048031/app.js                 
HTTP server is listening on http://localhost:3000

源代码:https ://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/53048031


推荐阅读