Mocha before()不从Express服务器监听事件发射器

时间:2018-04-15 01:43:45

标签: javascript node.js mocha

我正在学习为我的Node Express应用程序实现Mocha测试,但在我的服务器处理完一些代码之前遇到了我的测试执行问题。基本上,我希望我的服务器在加载后发出一个事件告诉我的Mocha框架,可以开始运行测试。

因此,在我的app.js文件中,我发布了一个事件:

let app = express();
app.use(require('./controllers'))    
var port = 8080
var httpServer = require('http').createServer(app);

httpServer.listen(port, function() {
    logger.info('Server started on port ' + port + '.');
    httpServer.emit("serverStarted");
    logger.info('Emitted action.')
});

module.exports.httpServer = httpServer;

在我的artworks.tests.js文件中,我有一个before()函数,只有在服务器准备开始测试后才调用done()

let chai = require('chai');
let chaiHttp = require('chai-http');
let logger = require('../util/logger');
let should = chai.should();

chai.use(chaiHttp);
const artworksController = require('../controllers/artworks');
var server = require('../app').httpServer;

    before(function (done) {
        server.on("serverStarted", function(){
            logger.info("Event listened to.")
            done();
        });
    });

但是,我的Mocha测试继续在before挂钩上失败:

  

mocha ** / artworks.test.js -t 10000

2018-04-15T01:35:00.709Z - info: Server started on port 8080.
2018-04-15T01:35:00.713Z - info: Emitted action.
2018-04-15T01:35:00.982Z - info: Connection to mongodb successful! The application is now connected to MONGO_DB_URL
  1) "before all" hook

  0 passing (10s)
  1 failing

  1)  "before all" hook:
     Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.As you can see, I've set the timeout to 10 seconds, plenty of time for the server to boot up. However, clearly, the `server` in my `artworks.tests.js` file is not listening to events being emitted. I expect that the `before()` function's `done()` after the server is started, and then I can begin performing my other tests. 

我跟随this tutorial,其他SO帖子引用的内容非常有助于确保测试仅在服务器完成启动后运行。

0 个答案:

没有答案