From 9ae68a93d28b736ea2c5dc7336b992478b1f758a Mon Sep 17 00:00:00 2001 From: Jacob Smith <3012099+JakobJingleheimer@users.noreply.github.com> Date: Mon, 27 May 2024 22:40:22 +0200 Subject: [PATCH] test: expose `file` & `fullName` props on TestContext (for snapshots) --- lib/internal/test_runner/test.js | 24 ++++++++++++++++++++ test/parallel/test-runner-snapshot-props.js | 25 +++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 test/parallel/test-runner-snapshot-props.js diff --git a/lib/internal/test_runner/test.js b/lib/internal/test_runner/test.js index effc73c0f2ca7d..e1574c65e7f2da 100644 --- a/lib/internal/test_runner/test.js +++ b/lib/internal/test_runner/test.js @@ -214,6 +214,30 @@ class TestContext { return this.#test.signal; } + /** + * Get the path of the current test file. + * @example '/tmp/test.js' + */ + get file() { + return this.#test.loc.file; + } + + /** + * Get the name for the current context and all ancestors (outputs a string from root to tip). + * @example 'Animals › Cat › sleep() should be possible at any time' + */ + get fullName() { + let fullName = this.#test.name; + let parent = this.#test.parent; + + while (parent.parent) { // `null` when at the root which has no name, so abort when we get there + fullName = `${parent.name} › ${fullName}`; + ({ parent } = parent); + } + + return fullName; + } + get name() { return this.#test.name; } diff --git a/test/parallel/test-runner-snapshot-props.js b/test/parallel/test-runner-snapshot-props.js new file mode 100644 index 00000000000000..20eefb9e467c61 --- /dev/null +++ b/test/parallel/test-runner-snapshot-props.js @@ -0,0 +1,25 @@ +'use strict'; +require('../common'); + +const assert = require('node:assert'); +const { resolve } = require('node:path'); +const { describe, test } = require('node:test'); + + +// These props are needed to support jest-like snapshots (which is not itself a feature in Core). + +const rootName = 'props for snapshots'; +describe(rootName, () => { + test('test context has "file" property', (ctx) => { + assert.strictEqual(ctx.file, resolve(__filename)); + }); + + const nestedName = '"fullName" contains both case and ancestor names'; + test(nestedName, (ctx) => { + assert.match(ctx.fullName, new RegExp(rootName)); + assert.match(ctx.fullName, new RegExp(nestedName)); + + // Ensure root appears before tip + assert.ok(ctx.fullName.indexOf(rootName) < ctx.fullName.indexOf(nestedName)); + }); +});