Skip to content

Commit ef174ea

Browse files
MoLowtargos
authored andcommitted
assert: callTracker throw a specific error message when possible
PR-URL: #43640 Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com> Reviewed-By: Nitzan Uziely <linkgoron@gmail.com> Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
1 parent e51d8c6 commit ef174ea

File tree

2 files changed

+36
-11
lines changed

2 files changed

+36
-11
lines changed

lib/internal/assert/calltracker.js

+9-5
Original file line numberDiff line numberDiff line change
@@ -88,12 +88,16 @@ 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 === 0) {
92+
return;
9693
}
94+
const message = errors.length === 1 ?
95+
errors[0].message :
96+
'Functions were not called the expected number of times';
97+
throw new AssertionError({
98+
message,
99+
details: errors,
100+
});
97101
}
98102
}
99103

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

+27-6
Original file line numberDiff line numberDiff line change
@@ -6,27 +6,48 @@ 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 = 'Functions 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.
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+
);
31+
callsbar();
32+
33+
// Will throw an error if callsfoo() and callsbar isn't called exactly once.
2434
tracker.verify();
2535

36+
const callsfoobar = tracker.calls(foo, 1);
37+
2638
callsfoo();
2739

28-
// Expects an error as callsfoo() was called more than once.
40+
// Expects an error as callsfoo() was called more than once and callsfoobar() was called less than one time.
41+
assert.throws(
42+
() => tracker.verify(),
43+
{ message: generic_msg }
44+
);
45+
46+
callsfoobar();
47+
48+
49+
// Expects an error as callsfoo() was called more than once
2950
assert.throws(
3051
() => tracker.verify(),
31-
{ message: msg }
52+
{ message: 'Expected the foo function to be executed 1 time(s) but was executed 2 time(s).' }
3253
);

0 commit comments

Comments
 (0)