Skip to content

Commit 3d6fcbb

Browse files
committed
assert: callTracker throw a specific error message when possible
1 parent 736a7d8 commit 3d6fcbb

File tree

2 files changed

+32
-12
lines changed

2 files changed

+32
-12
lines changed

lib/internal/assert/calltracker.js

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -88,12 +88,17 @@ class CallTracker {
8888

8989
verify() {
9090
const errors = this.report();
91-
if (errors.length > 0) {
92-
throw new AssertionError({
93-
message: 'Function(s) were not called the expected number of times',
94-
details: errors,
95-
});
91+
if (!errors.length) {
92+
return;
9693
}
94+
let message = 'Function(s) were not called the expected number of times';
95+
if (errors.length === 1) {
96+
message = errors[0].message;
97+
}
98+
throw new AssertionError({
99+
message,
100+
details: errors,
101+
});
97102
}
98103
}
99104

test/parallel/test-assert-calltracker-verify.js

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,27 +6,42 @@ const assert = require('assert');
66

77
const tracker = new assert.CallTracker();
88

9-
const msg = 'Function(s) were not called the expected number of times';
9+
const generic_msg = 'Function(s) were not called the expected number of times';
1010

1111
function foo() {}
1212

13+
function bar() {}
14+
1315
const callsfoo = tracker.calls(foo, 1);
16+
const callsbar = tracker.calls(bar, 1);
1417

15-
// Expects an error as callsfoo() was called less than one time.
18+
// Expects an error as callsfoo() and callsbar() were called less than one time.
1619
assert.throws(
1720
() => tracker.verify(),
18-
{ message: msg }
21+
{ message: generic_msg }
1922
);
2023

2124
callsfoo();
2225

23-
// Will throw an error if callsfoo() isn't called exactly once.
24-
tracker.verify();
26+
// Expects an error as callsbar() was called less than one time.
27+
assert.throws(
28+
() => tracker.verify(),
29+
{ message: 'Expected the bar function to be executed 1 time(s) but was executed 0 time(s).' }
30+
);
2531

2632
callsfoo();
2733

28-
// Expects an error as callsfoo() was called more than once.
34+
// Expects an error as callsfoo() was called more than once and callsbar() was called less than one time.
35+
assert.throws(
36+
() => tracker.verify(),
37+
{ message: generic_msg }
38+
);
39+
40+
callsbar();
41+
42+
43+
// Expects an error as callsfoo() was called more than once
2944
assert.throws(
3045
() => tracker.verify(),
31-
{ message: msg }
46+
{ message: 'Expected the foo function to be executed 1 time(s) but was executed 2 time(s).' }
3247
);

0 commit comments

Comments
 (0)