Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

assert: callTracker throw a specific error message when possible #43640

Merged
merged 3 commits into from
Jul 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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).' }
);