Skip to content

Commit 18f8c2c

Browse files
committed
test_runner: allow assert.ok to check deeper into the stacktrace
1 parent 2bd6a57 commit 18f8c2c

File tree

2 files changed

+22
-7
lines changed

2 files changed

+22
-7
lines changed

lib/assert.js

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -282,20 +282,34 @@ function parseCode(code, offset) {
282282
throw null;
283283
}
284284

285+
function getInvokingCall(stack) {
286+
// Try to get the userland function that invoked this assertion
287+
for (let i = 0; i < stack.length; i++) {
288+
const call = stack[i];
289+
const filename = call.getFileName();
290+
if (StringPrototypeStartsWith(filename, 'node:') && BuiltinModule.exists(StringPrototypeSlice(filename, 5))) {
291+
continue;
292+
} else return call;
293+
}
294+
// If that's not possible, just return the function that did.
295+
return stack[0];
296+
}
297+
285298
function getErrMessage(message, fn) {
286299
const tmpLimit = Error.stackTraceLimit;
287300
const errorStackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
288301
// Make sure the limit is set to 1. Otherwise it could fail (<= 0) or it
289-
// does to much work.
290-
if (errorStackTraceLimitIsWritable) Error.stackTraceLimit = 1;
302+
// does to much work. The limit is set to 2, as this allows any wrappers
303+
// around this assertion function to be skipped.
304+
if (errorStackTraceLimitIsWritable) Error.stackTraceLimit = 2;
291305
// We only need the stack trace. To minimize the overhead use an object
292306
// instead of an error.
293307
const err = {};
294308
ErrorCaptureStackTrace(err, fn);
295309
if (errorStackTraceLimitIsWritable) Error.stackTraceLimit = tmpLimit;
296310

297311
overrideStackTrace.set(err, (_, stack) => stack);
298-
const call = err.stack[0];
312+
const call = getInvokingCall(err.stack);
299313

300314
let filename = call.getFileName();
301315
const line = call.getLineNumber() - 1;
@@ -305,10 +319,7 @@ function getErrMessage(message, fn) {
305319

306320
if (filename) {
307321
identifier = `${filename}${line}${column}`;
308-
309-
// Skip Node.js modules!
310-
if (StringPrototypeStartsWith(filename, 'node:') &&
311-
BuiltinModule.exists(StringPrototypeSlice(filename, 5))) {
322+
if (StringPrototypeStartsWith(filename, 'node:') && BuiltinModule.exists(StringPrototypeSlice(filename, 5))) {
312323
errorCache.set(identifier, undefined);
313324
return;
314325
}

test/parallel/test-runner-assert.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,7 @@ test('only methods from node:assert are on t.assert', (t) => {
2424
'throws',
2525
]);
2626
});
27+
28+
test('t.assert.ok correctly parses the stacktrace', (t) => {
29+
t.assert.throws(() => t.assert.ok(1 === 2), /t\.assert\.ok\(1 === 2\)/);
30+
});

0 commit comments

Comments
 (0)