Skip to content

Commit

Permalink
assert: callTracker throw a specific error message when possible
Browse files Browse the repository at this point in the history
PR-URL: #43640
Reviewed-By: Antoine du Hamel <[email protected]>
Reviewed-By: Nitzan Uziely <[email protected]>
Reviewed-By: Benjamin Gruenbaum <[email protected]>
  • Loading branch information
MoLow authored and targos committed Jul 31, 2022
1 parent db53e9b commit 480a754
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 11 deletions.
14 changes: 9 additions & 5 deletions lib/internal/assert/calltracker.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
});
}
}

Expand Down
33 changes: 27 additions & 6 deletions test/parallel/test-assert-calltracker-verify.js
Original file line number Diff line number Diff line change
Expand Up @@ -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).' }
);

0 comments on commit 480a754

Please sign in to comment.