I need to test a socket server and a socket client made with socket.io, i was following the official documentation, in the example they created the server and client before each test, so for individual testing (previous client or server) I adapted the code importing the real instance from my code:
For server: (The http server is already up when imported)
import { describe, it, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { io } from 'socketServer.js'
import { io as Client } from 'socket.io-client'
const { SERVICE } = process.env
const port = SERVICE === 'IP' ? 3000 : 3005
describe('Socket.io client tests', () => {
let serverSocket, clientSocket
before((done) => {
clientSocket = Client(`http://localhost:${port}`)
io.on('connection', (socket) => {
serverSocket = socket
})
clientSocket.connect()
clientSocket.on('connect', done)
console.log(clientSocket.connected)
})
after(() => {
io?.close()
clientSocket?.close()
})
it('should work', (done) => {
console.log(clientSocket.connected)
clientSocket?.on('packagesCounter', (arg) => {
console.log('arg', arg)
assert.equal(arg, 0)
done()
})
})
})
For client:
import { describe, it, beforeEach, afterEach } from 'node:test'
import assert from 'node:assert/strict'
import { createServer } from 'http'
import { Server } from 'socket.io'
import { socket as clientSocket } from 'socketClient.js'
describe('Socket.io client tests', () => {
let io, serverSocket
before((done) => {
const httpServer = createServer()
io = new Server(httpServer)
httpServer.listen(3000, () => {
io.on('connection', (socket) => {
serverSocket = socket
})
clientSocket.connect()
console.log('in before', clientSocket.connected)
clientSocket.on('connect', done)
})
})
after(() => {
io?.close()
clientSocket?.close()
})
it('should work', (done) => {
console.log('in test', clientSocket.connected)
clientSocket?.on('hello', (arg) => {
assert.equal(arg, 'world')
done()
})
serverSocket?.emit('hello', 'world')
})
})
These are super simple scripts at the moment, but in neither the server seems to be listening to connections, therefore the client never connects and the test "passes" but just because the actual assertion never executes.
So, how I manage to actually create the server in the "before hook" and listen to connections?
Thanks in advance for the help guys.