From bb3d0b23ab89cf90ac2977403d74bb755f4f6b07 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Mon, 2 Oct 2023 21:01:01 +0200 Subject: [PATCH] test: use sinon stub to simplify code MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- tests/worker/cluster-worker.test.mjs | 14 ++++++++------ tests/worker/thread-worker.test.mjs | 13 +++++++------ 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/tests/worker/cluster-worker.test.mjs b/tests/worker/cluster-worker.test.mjs index f6a927aa..9349743c 100644 --- a/tests/worker/cluster-worker.test.mjs +++ b/tests/worker/cluster-worker.test.mjs @@ -1,17 +1,19 @@ import { expect } from 'expect' +import { restore, stub } from 'sinon' import { ClusterWorker } from '../../lib/index.js' describe('Cluster worker test suite', () => { - let numberOfMessagesSent = 0 - const send = () => { - ++numberOfMessagesSent - } + const sendStub = stub().returns() class SpyWorker extends ClusterWorker { getMainWorker () { - return { send } + return { send: sendStub } } } + afterEach(() => { + restore() + }) + it('Verify that handleError() method is working properly', () => { const error = new Error('Error as an error') const worker = new ClusterWorker(() => {}) @@ -24,6 +26,6 @@ describe('Cluster worker test suite', () => { it('Verify worker invokes the getMainWorker() and send() methods', () => { const worker = new SpyWorker(() => {}) worker.sendToMainWorker({ ok: 1 }) - expect(numberOfMessagesSent).toBe(1) + expect(worker.getMainWorker().send.calledOnce).toBe(true) }) }) diff --git a/tests/worker/thread-worker.test.mjs b/tests/worker/thread-worker.test.mjs index 4be262a2..6121995b 100644 --- a/tests/worker/thread-worker.test.mjs +++ b/tests/worker/thread-worker.test.mjs @@ -1,18 +1,19 @@ import { expect } from 'expect' +import { restore, stub } from 'sinon' import { ThreadWorker } from '../../lib/index.js' describe('Thread worker test suite', () => { - let numberOfMessagesPosted = 0 - const postMessage = () => { - ++numberOfMessagesPosted - } class SpyWorker extends ThreadWorker { constructor (fn) { super(fn) - this.port = { postMessage } + this.port = { postMessage: stub().returns() } } } + afterEach(() => { + restore() + }) + it('Verify that handleError() method is working properly', () => { const error = new Error('Error as an error') const worker = new ThreadWorker(() => {}) @@ -25,6 +26,6 @@ describe('Thread worker test suite', () => { it('Verify worker invokes the postMessage() method on port property', () => { const worker = new SpyWorker(() => {}) worker.sendToMainWorker({ ok: 1 }) - expect(numberOfMessagesPosted).toBe(1) + expect(worker.port.postMessage.calledOnce).toBe(true) }) }) -- 2.34.1