在开始摩卡测试之前,请确保Express应用程序正在运行

问题描述

我使用express和node.js构建了一个沙发数据库的API。我的问题是,当我运行测试时,其中一些失败,因为服务器未完全运行。我在https://mrvautin.com/ensure-express-app-started-before-tests处找到了有关如何解决此问题的解决方案。文章指出,为了解决此问题,您必须像这样在服务器文件添加事件发射器

app.listen(app_port,app_host,function () {
    console.log('App has started');
    app.emit("appStarted");
});

然后将其添加到测试文件

before(function (done) {
    app.on("appStarted",function(){
        done();
    });
});

我已经尝试过了,这是我的实现方式

服务器文件

app.listen(config['server']['port'],function(){
    app.emit("appStarted");
    logger.info("Listening")
})

测试文件

before(function(done){
    app.on("appStarted",function(){
        done();
    })
});

我不断遇到以下错误

  1) "before all" hook in "{root}":
     Error: Timeout of 2000ms exceeded. For async tests and hooks,ensure "done()" is called; if returning a Promise,ensure it resolves.
      at listOnTimeout (internal/timers.js:549:17)
      at processtimers (internal/timers.js:492:7)

文章来自2016年,所以我在想语法可能已被弃用。我想知道是否有人可以帮助我指出正确的方向?

解决方法

您可以添加以下条件,更多信息请参见"Accessing the main module".

if (require.main === module) {
     // this module was run directly from the command line as in node xxx.js
} else {
     // this module was not run directly from the command line and probably loaded by something else
}

例如

index.ts

import express from 'express';

const app = express();
const port = 3000;

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

if (require.main === module) {
  app.listen(port,() => {
    console.log('App has started');
  });
}

export { app,port };

index.test.ts

import { app,port } from './';
import http from 'http';
import request from 'supertest';

describe('63822664',() => {
  let server: http.Server;
  before((done) => {
    server = app.listen(port,() => {
      console.log('App has started');
      done();
    });
  });
  after((done) => {
    server.close(done);
    console.log('App has closed');
  });
  it('should pass',() => {
    return request(server)
      .get('/')
      .expect(200);
  });
});

集成测试结果:

(node:22869) ExperimentalWarning: The fs.promises API is experimental
  63822664
App has started
    ✓ should pass
App has closed


  1 passing (26ms)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...