From c28c57767f1a7bb4c5cf5a2bd32ab7c601525dd7 Mon Sep 17 00:00:00 2001 From: siiky Date: Wed, 11 Dec 2024 19:44:22 +0000 Subject: [PATCH] refactor: improve basic bill validator tests --- lib/hardware-testing/bill-validator.js | 64 ++++++++++++++++++++++---- 1 file changed, 55 insertions(+), 9 deletions(-) diff --git a/lib/hardware-testing/bill-validator.js b/lib/hardware-testing/bill-validator.js index 21dfe84bf..0b844f01d 100644 --- a/lib/hardware-testing/bill-validator.js +++ b/lib/hardware-testing/bill-validator.js @@ -15,6 +15,41 @@ const BOXES = { recyclers: 0, } +const addEventListeners = (validator, reject, eventListenersToAdd) => { + const allEvents = [ + 'actionRequiredMaintenance', + 'billsAccepted', + 'billsRead', + 'billsRejected', + 'billsValid', + 'cashSlotRemoveBills', + 'disconnected', + 'enabled', + 'error', + 'jam', + 'leftoverBillsInCashSlot', + 'stackerClosed', + 'stackerOpen', + 'standby', + ] + + const handleUnexpected = eventName => (...eventArguments) => { + const error = new Error("Unexpected event received") + error.eventName = eventName + error.eventArguments = [...eventArguments] + reject(error) + } + + allEvents.forEach( + ev => validator.on(ev, eventListenersToAdd[ev] ?? handleUnexpected) + ) +} + +const doFinally = validator => () => { + validator.removeAllListeners() + validator.disable() +} + const testEnable = validator => () => new Promise( (resolve, reject) => { let accepted = false @@ -23,14 +58,15 @@ const testEnable = validator => () => new Promise( validator.enable() } - validator.on('billsAccepted', () => { accepted = true }) - validator.on('billsRead', bills => resolve({ accepted, bills })) - validator.on('billsRejected', () => enable()) - validator.on('error', error => reject({ accepted, error })) + addEventListeners(validator, reject, { + billsAccepted: () => { accepted = true }, + billsRead: bills => resolve({ accepted, bills }), + billsRejected: () => enable(), + }) enable() } -).finally(() => validator.removeAllListeners()) +).finally(doFinally(validator)) const steps = () => new Promise((resolve, reject) => { @@ -51,9 +87,14 @@ const steps = () => { name: 'reject', - instructionMessage: `Try to insert a ${FIAT_CODE} bill...`, confirmationMessage: "Did the validator reject the bill?", - test: () => validator.reject(), + test: () => + new Promise((resolve, reject) => { + addEventListeners(validator, reject, { + billsRejected: () => resolve(), + }) + validator.reject() + }).finally(doFinally(validator)), }, { @@ -65,9 +106,14 @@ const steps = () => { name: 'stack', - instructionMessage: `Try to insert a ${FIAT_CODE} bill...`, confirmationMessage: "Did the validator stack the bill?", - test: () => validator.stack(), + test: () => + new Promise((resolve, reject) => { + addEventListeners(validator, reject, { + billsValid: () => resolve(), + }) + validator.stack() + }).finally(doFinally(validator)), }, ])