Friday, 19 October 2018

expressJS/jestJS: How to split get() function to write simple jest unit test?

How do I define a get() routing in an expressJS application with the intention of doing easy unit testing?

So as a first step I moved the function of get() in an 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 // id is in this example '1'
    req.app.locals['target' + id].pwmWrite(value))
    getStatus(app, io)
    res.send({ value }) // don't need this
  }
}

So first of all I'm not quite sure, if I split that code correctly - thinking of doing unit testing.

For me the only thing which has to be done by calling /set-status?id=1&value=50 is to call pwmWrite() for an (I guess) object, which is defined by new Gpio and stored in locals of expressJS.

And for the second: If this should be the correct way, I do not understand how to write a jestJS unit test to check if pwmWrite has been called - which is inside of an asyncronous function.

This is my attempt, but I can't test for the inside call of pwmWrite:

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()
})



from expressJS/jestJS: How to split get() function to write simple jest unit test?

No comments:

Post a Comment