I have an express.js server which uses a database for storage. Clients can read and write the data via http endpoints. Clients can also listen for changes to the data via socket.io.
My pared down code:
socket.io event handlers
export default (io, store, db) => {
io.on('connection', function(socket){
socket.on('disconnect', function() {
logger.log("Disconnect. Socket count: " + count)
// logic which removes socket
})
socket.on('observe', function(json){
logger.log("Observe " + collection)
// logic which stores socket for later updates
// logic which gets the current data from the database
socket.emit('change', {theLatestData})
})
})
}
socket.io client
var socket = io("http://localhost:8080")
socket.emit('observe', 'collectionName')
socket.on('change', function(data) {
// logic which does something with the data
})
HTTP endpoint:
api.post('/collection/:collection', (req, res) => {
// logic which adds some data to a collection in the db
// logic which emits updates the attached sockets
})
It all appears to work well, but there is no code coverage on the logic in the event handlers.
I'd like to write mocha tests that assert when a socket connects to the server it gets the latest data, and when a socket connects to the server, the number of attached sockets increases and so on.
However, I cannot figure out a suitable approach to write these tests. I realise I could extract the handler logic into modules and test them in isolation, but I'd really like the tests to actually run through the event handlers.
Should I be actually starting the server in the test and attaching a socket? Is there a way to attach a mock socket and somehow trigger the observe and disconnect events therefore exercising the logic in the handlers.
I've looked at similar questions and answers on SO but they haven't really help me so far.
Aucun commentaire:
Enregistrer un commentaire