add jest mocks example for gpio+mqtt client

This commit is contained in:
Frieder Schlesier 2022-11-10 23:21:41 +01:00
parent f2d3961686
commit bcbf9e6f88
4 changed files with 51 additions and 4 deletions

View File

@ -12,7 +12,7 @@ Article: https://www.sitepoint.com/getting-started-with-the-raspberry-pi-gpio-pi
docker run -it --rm -v $(pwd):/app -w /app node:lts bash docker run -it --rm -v $(pwd):/app -w /app node:lts bash
~~~ ~~~
followed by followed by
~~~shell ~~~shell
npm install npm install
@ -21,10 +21,14 @@ npm run test
## Jest ## Jest
https://jestjs.io/docs/using-matchers - https://jestjs.io/docs/using-matchers
- https://dev.to/zaklaughton/the-only-3-steps-you-need-to-mock-an-api-call-in-jest-39mb
- https://jestjs.io/docs/mock-functions#mocking-modules
## TODO ## TODO
idea: mock functions of `onoff` to test behaviour of functions which rely on GPIO being low/high
check this out: https://stackoverflow.com/questions/50066138/mock-fs-function-with-jest check this out: https://stackoverflow.com/questions/50066138/mock-fs-function-with-jest
is this going to be a problem? https://stackoverflow.com/questions/62568294/nodejs-fs-watch-inside-docker-container-detects-changes-twice is this going to be a problem? https://stackoverflow.com/questions/62568294/nodejs-fs-watch-inside-docker-container-detects-changes-twice

27
action-on-gpio.js Normal file
View File

@ -0,0 +1,27 @@
const Gpio = require('onoff').Gpio;
const mqtt = require('mqtt');
const actiontrigger = {
/**
* those arguments should be part of the object
* which should also be mockabke
* @param {onoff.Gpio} gpio
* @param {mqtt.Client} client
*/
pubMqttOnGpio (gpio, client) {
console.log('gpio: ');
if (gpio.readSync() === Gpio.LOW) {
client.publish('button/islow', '{true}', {qos: 1})
}
},
sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
}
module.exports = actiontrigger

16
action-on-gpio.test.js Normal file
View File

@ -0,0 +1,16 @@
const Gpio = require('onoff').Gpio;
const action = require('./action-on-gpio');
// https://stackoverflow.com/questions/51418086/jest-expected-mock-function-to-have-been-called-but-it-was-not-called
describe('integration test', () => {
it('should publish mqtt when GPIO goes high', () => {
const button = { readSync: jest.fn(() => Gpio.LOW)}
const client = { publish: jest.fn()}
action.pubMqttOnGpio(button, client);
expect(button.readSync).toHaveBeenCalledTimes(1)
expect(client.publish).toHaveBeenCalledTimes(1)
expect(client.publish).toBeCalledWith('button/islow', '{true}', {qos: 1})
})
})

View File

@ -5,7 +5,6 @@
"scripts": { "scripts": {
"start": "node app.js", "start": "node app.js",
"test": "jest" "test": "jest"
}, },
"author": { "author": {
"name": "CR", "name": "CR",
@ -17,6 +16,7 @@
}, },
"dependencies": { "dependencies": {
"fix": "^0.0.6", "fix": "^0.0.6",
"mqtt": "^4.3.7" "mqtt": "^4.3.7",
"onoff": "^6.0.3"
} }
} }