【发布时间】:2017-11-03 11:23:43
【问题描述】:
我正在使用 mocha 在 nodejs 8.9 上测试带有服务器和客户端组件的 nodejs-app。
为了让 mocha 正确结束,我必须确保在运行测试后关闭所有 socketio 和 http-servers。这适用于普通测试,但是一旦我向 socketio-server 注册了一个中间件,mocha 进程就不会关闭并永远保持打开状态。
测试代码(在第二个测试中评论以查看问题,通过mocha test.spec.js运行):
// test.spec.js
'use strict'
const Express = require('express')
const Http = require('http')
const ioserver = require('socket.io')
const ioclient = require('socket.io-client')
const NODE_PORT = process.env.NODE_PORT || 3000
describe('Client', function () {
beforeEach(() => {
const express = new Express()
this._http = Http.Server(express)
this._ioserver = ioserver(this._http)
this._http.listen(NODE_PORT)
})
// this test works perfectly, even when I copy it and run it
// multiple times in this suite
it('should connect to a socketio-server', (done) => {
this._ioserver.on('connection', () => {
client.close()
done()
})
const client = ioclient.connect(`http://localhost:${NODE_PORT}`)
})
// this test also finished, but the suite hangs afterwards - as if
// a socket-client or socket-server was not closed properly.
it('should finish the test suite even with a middleware', (done) => {
this._ioserver.use((socket, next) => {
return next()
})
this._ioserver.on('connection', () => {
client.close()
done()
})
const client = ioclient.connect(`http://localhost:${NODE_PORT}`)
})
afterEach(() => {
this._ioserver.close()
this._http.close()
})
})
你知道为什么会这样吗?
【问题讨论】:
-
我使用
client.disconnect()而不是close()也许这就是原因。 -
这两个是同义词,调用相同的方法
-
打开了一个错误报告:github.com/mochajs/mocha/issues/3095
标签: node.js socket.io mocha.js middleware