Skip to content

Commit 9ae68a9

Browse files
test: expose file & fullName props on TestContext (for snapshots)
1 parent 8e9686d commit 9ae68a9

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

lib/internal/test_runner/test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,30 @@ class TestContext {
214214
return this.#test.signal;
215215
}
216216

217+
/**
218+
* Get the path of the current test file.
219+
* @example '/tmp/test.js'
220+
*/
221+
get file() {
222+
return this.#test.loc.file;
223+
}
224+
225+
/**
226+
* Get the name for the current context and all ancestors (outputs a string from root to tip).
227+
* @example 'Animals › Cat › sleep() should be possible at any time'
228+
*/
229+
get fullName() {
230+
let fullName = this.#test.name;
231+
let parent = this.#test.parent;
232+
233+
while (parent.parent) { // `null` when at the root which has no name, so abort when we get there
234+
fullName = `${parent.name}${fullName}`;
235+
({ parent } = parent);
236+
}
237+
238+
return fullName;
239+
}
240+
217241
get name() {
218242
return this.#test.name;
219243
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
'use strict';
2+
require('../common');
3+
4+
const assert = require('node:assert');
5+
const { resolve } = require('node:path');
6+
const { describe, test } = require('node:test');
7+
8+
9+
// These props are needed to support jest-like snapshots (which is not itself a feature in Core).
10+
11+
const rootName = 'props for snapshots';
12+
describe(rootName, () => {
13+
test('test context has "file" property', (ctx) => {
14+
assert.strictEqual(ctx.file, resolve(__filename));
15+
});
16+
17+
const nestedName = '"fullName" contains both case and ancestor names';
18+
test(nestedName, (ctx) => {
19+
assert.match(ctx.fullName, new RegExp(rootName));
20+
assert.match(ctx.fullName, new RegExp(nestedName));
21+
22+
// Ensure root appears before tip
23+
assert.ok(ctx.fullName.indexOf(rootName) < ctx.fullName.indexOf(nestedName));
24+
});
25+
});

0 commit comments

Comments
 (0)