How can I define a get() route in an Express.js application for easy unit testing?
To start, I extracted the get()
function into its own file:
index.js
const express = require('express')
const socketIo = require('socket.io')
const Gpio = require('pigpio').Gpio
const app = express()
const server = http.createServer(app)
const io = socketIo(server)
const setStatus = require('./lib/setStatus.js')
app.locals['target1'] = new Gpio(1, { mode: Gpio.OUTPUT })
app.get('/set-status', setStatus(app, io))
lib/setStatus.js
const getStatus = require('./getStatus.js')
module.exports = (app, io) => {
return (req, res) => {
const { id, value } = req.query
req.app.locals['target' + id].pwmWrite(value)
getStatus(app, io)
res.send({ value })
}
}
lib/getStatus.js
const pins = require('../config.js').pins
module.exports = async (app, socket) => {
const result = []
pins.map((pin, index) => {
result.push(app.locals['target' + (index + 1)].getPwmDutyCycle())
})
socket.emit('gpioStatus', result)
}
I'm unsure if I separated the code correctly for unit testing purposes.
When calling /set-status?id=1&value=50
, the expected action is to call pwmWrite()
on an object defined by new Gpio
stored in Express.js locals.
However, I'm uncertain how to write a Jest unit test to verify the internal call to pwmWrite
within an asynchronous function.
This is my current attempt, but I'm struggling to test the pwmWrite call inside an async function:
test('should call pwmWrite() and getStatus()', async () => {
const app = {}
const io = { emit: jest.fn() }
const req = {
app: {
locals: {
target1: { pwmWrite: jest.fn() }
}
}
}
}
expect.assertions(1)
expect(req.app.locals.target1.pwmWrite).toHaveBeenCalled()
await expect(getStatus(app, io)).toHaveBeenCalled()
})