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
  • Loading branch information
MoLow committed Jul 3, 2022
1 parent 71691e5 commit 0b3b3cd
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 12 deletions.
15 changes: 10 additions & 5 deletions lib/internal/assert/calltracker.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
});
}
}

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

0 comments on commit 0b3b3cd

Please sign in to comment.