From 40e1795fea16dc6b3d86a23b6b7958b1fdf99926 Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Fri, 8 Jul 2022 13:17:35 +0300 Subject: [PATCH] assert: callTracker throw a specific error message when possible PR-URL: https://github.com/nodejs/node/pull/43640 Reviewed-By: Antoine du Hamel Reviewed-By: Nitzan Uziely Reviewed-By: Benjamin Gruenbaum --- lib/internal/assert/calltracker.js | 14 +++++--- .../test-assert-calltracker-verify.js | 33 +++++++++++++++---- 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/lib/internal/assert/calltracker.js b/lib/internal/assert/calltracker.js index f00f2e33271980..cf53b1af10fe28 100644 --- a/lib/internal/assert/calltracker.js +++ b/lib/internal/assert/calltracker.js @@ -88,12 +88,16 @@ class CallTracker { verify() { const errors = this.report(); - if (errors.length > 0) { - throw new AssertionError({ - message: 'Function(s) were not called the expected number of times', - details: errors, - }); + if (errors.length === 0) { + return; } + const message = errors.length === 1 ? + errors[0].message : + 'Functions were not called the expected number of times'; + throw new AssertionError({ + message, + details: errors, + }); } } diff --git a/test/parallel/test-assert-calltracker-verify.js b/test/parallel/test-assert-calltracker-verify.js index 75d20bf9c49c38..118f04f7352780 100644 --- a/test/parallel/test-assert-calltracker-verify.js +++ b/test/parallel/test-assert-calltracker-verify.js @@ -6,27 +6,48 @@ const assert = require('assert'); const tracker = new assert.CallTracker(); -const msg = 'Function(s) were not called the expected number of times'; +const generic_msg = 'Functions were not called the expected number of times'; function foo() {} +function bar() {} + const callsfoo = tracker.calls(foo, 1); +const callsbar = tracker.calls(bar, 1); -// Expects an error as callsfoo() was called less than one time. +// Expects an error as callsfoo() and callsbar() were called less than one time. assert.throws( () => tracker.verify(), - { message: msg } + { message: generic_msg } ); callsfoo(); -// Will throw an error if callsfoo() isn't called exactly once. +// Expects an error as callsbar() was called less than one time. +assert.throws( + () => tracker.verify(), + { message: 'Expected the bar function to be executed 1 time(s) but was executed 0 time(s).' } +); +callsbar(); + +// Will throw an error if callsfoo() and callsbar isn't called exactly once. tracker.verify(); +const callsfoobar = tracker.calls(foo, 1); + callsfoo(); -// Expects an error as callsfoo() was called more than once. +// Expects an error as callsfoo() was called more than once and callsfoobar() was called less than one time. +assert.throws( + () => tracker.verify(), + { message: generic_msg } +); + +callsfoobar(); + + +// Expects an error as callsfoo() was called more than once assert.throws( () => tracker.verify(), - { message: msg } + { message: 'Expected the foo function to be executed 1 time(s) but was executed 2 time(s).' } );