From 0b3b3cda3769e9d9a6a0138a8205098c1a26d50b Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Fri, 1 Jul 2022 10:32:10 +0300 Subject: [PATCH] assert: callTracker throw a specific error message when possible --- lib/internal/assert/calltracker.js | 15 ++++++---- .../test-assert-calltracker-verify.js | 29 ++++++++++++++----- 2 files changed, 32 insertions(+), 12 deletions(-) diff --git a/lib/internal/assert/calltracker.js b/lib/internal/assert/calltracker.js index f00f2e33271980..2ab0f0e5da6942 100644 --- a/lib/internal/assert/calltracker.js +++ b/lib/internal/assert/calltracker.js @@ -88,12 +88,17 @@ 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) { + return; } + let message = 'Function(s) were not called the expected number of times'; + if (errors.length === 1) { + message = errors[0].message; + } + 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..3856668830edb0 100644 --- a/test/parallel/test-assert-calltracker-verify.js +++ b/test/parallel/test-assert-calltracker-verify.js @@ -6,27 +6,42 @@ const assert = require('assert'); const tracker = new assert.CallTracker(); -const msg = 'Function(s) were not called the expected number of times'; +const generic_msg = 'Function(s) 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. -tracker.verify(); +// 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).' } +); callsfoo(); -// Expects an error as callsfoo() was called more than once. +// Expects an error as callsfoo() was called more than once and callsbar() was called less than one time. +assert.throws( + () => tracker.verify(), + { message: generic_msg } +); + +callsbar(); + + +// 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).' } );