diff --git a/README.md b/README.md index 802d397..3438019 100644 --- a/README.md +++ b/README.md @@ -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 ~~~ -followed by +followed by ~~~shell npm install @@ -21,10 +21,14 @@ npm run test ## 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 +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 is this going to be a problem? https://stackoverflow.com/questions/62568294/nodejs-fs-watch-inside-docker-container-detects-changes-twice diff --git a/action-on-gpio.js b/action-on-gpio.js new file mode 100644 index 0000000..7c35254 --- /dev/null +++ b/action-on-gpio.js @@ -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 diff --git a/action-on-gpio.test.js b/action-on-gpio.test.js new file mode 100644 index 0000000..1a8a163 --- /dev/null +++ b/action-on-gpio.test.js @@ -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}) + }) +}) \ No newline at end of file diff --git a/package.json b/package.json index 6b536b7..79eb400 100644 --- a/package.json +++ b/package.json @@ -5,7 +5,6 @@ "scripts": { "start": "node app.js", "test": "jest" - }, "author": { "name": "CR", @@ -17,6 +16,7 @@ }, "dependencies": { "fix": "^0.0.6", - "mqtt": "^4.3.7" + "mqtt": "^4.3.7", + "onoff": "^6.0.3" } }