我正在尝试使用Mocha编写一些测试,以测试使用Node.js和Socket.io编写的应用程序的某些功能。
到目前为止,我的服务器端代码下面带有测试用例的代码,它们在从浏览器环境连接时可以正常工作(是的,肯定在https://localhost:8089/
上监听了socket.io服务器)
Socket.io服务器
const dev = true
function createDev() {
console.log('SERVER will be initialized on development mode')
const key = fs.readFileSync('/Users/myowngrave/server.key'),
cert = fs.readFileSync('/Users/myowngrave/server.crt'),
credentials = { key, cert }
return https.createServer(credentials, app)
}
function createProd() {
return http.createServer(app)
}
const server = dev ? createDev() : createProd(),
io = socketIO(server)
console.log('ready now')
server.listen(8089)
server.emit('vthAppReady')
module.exports = server
单元测试
import io from 'socket.io-client'
describe('Upload image using socket.io', function() {
let img,
socket,
ioOptions = {
forceNew: true,
key: fs.readFileSync('server.key'),
ca: fs.readFileSync('server.crt')
}
before(function(done) {
this.timeout(10000)
server.on('vthAppReady', function() {
console.log('Oh la la LOL')
socket = io('https://localhost:8089/', ioOptions)
socket.on('error', err => done(err))
socket.on('connect', done)
})
})
after(function(done) {
if (socket.connected) socket.disconnect()
// just terminate https server
server.emit('vthAppClose', done)
})
})
由于“立即可用” 和“哦,大声笑”,我确定服务器端代码可以正常工作在运行测试用例时显示。但是没有触发来自测试用例代码的“ connect” 事件,这不走运。 “之前所有” 挂钩已超时。
Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (/Users/myowngrave/WebstormProjects/vaithuhay-app/test/upload.socket.spec.js)
我不知道我在做什么错。如何修复以使测试用例正常运行?