如何在expressJS应用程序中定义get()路由,以进行简单的单元测试?
因此,第一步,我将get()
的功能移到了自己的文件中:
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
}
}
lib/getStatus.js
const pins = require('../config.js').pins
module.exports = async (app, socket) => {
const res = []
pins.map((p, index) => {
res.push(app.locals['target' + (index + 1)].getPwmDutyCycle())
})
socket.emit('gpioStatus', res)
}
所以首先我不确定,如果我正确地拆分了该代码,请考虑进行单元测试。
对我来说,唯一需要通过调用
/set-status?id=1&value=50
来完成的事情就是为一个(我猜)对象调用pwmWrite()
,该对象由new Gpio
定义并存储在expressJS的locals
中。第二点:如果这是正确的方法,我不明白如何编写jestJS单元测试来检查是否已调用
pwmWrite
-这是在异步函数内部。这是我的尝试,但是我无法测试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()
})
最佳答案
您非常亲密,只是缺少了一些东西。
您需要在Expect语句之前调用setStatus
和getStatus
方法,
并且您缺少req.query
和res
上的模拟,因为getStatus
使用了它们。
test('should call pwmWrite() and getStatus()', async () => {
const app = {}
const io = {};
const req = {
query: {
id: '1',
name: 'foo'
},
app: {
locals: {
target1: { pwmWrite: jest.fn() }
}
}
};
const res = { send: jest.fn() };
// Mock getStatus BEFORE requiring setStatus
jest.mock('./getStatus');
//OBS Use your correct module paths
const setStatus = require('./setStatus');
const getStatus = require('./getStatus');
// Call methods
setStatus(app, io)(req, res);
expect.assertions(2);
// Get called in setStatus
expect(req.app.locals.target1.pwmWrite).toHaveBeenCalled();
// See if mocked getStatus has been called
await expect(getStatus).toHaveBeenCalled();
});
在需要
getStatus
之前,需要对setStatus
进行模拟,因为在那里使用了ojit_code关于javascript - expressJS/jestJS : How to split get() function to write simple jest unit test?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52842582/