Skip to content

Commit ac2b747

Browse files
committed
test_runner: add initial test_runner module
This commit adds a new test_runner module that exposes an API for creating JavaScript tests. As the tests execute, TAP output is written to standard output. This commit only supports executing individual test files, and does not implement command line functionality for a full test runner.
1 parent 6d3920d commit ac2b747

16 files changed

+1624
-0
lines changed

doc/api/errors.md

+8
Original file line numberDiff line numberDiff line change
@@ -2551,6 +2551,14 @@ An unspecified or non-specific system error has occurred within the Node.js
25512551
process. The error object will have an `err.info` object property with
25522552
additional details.
25532553

2554+
<a id="ERR_TEST_FAILURE"></a>
2555+
2556+
### `ERR_TEST_FAILURE`
2557+
2558+
This error represents a failed test. Additional information about the failure
2559+
is available via the `cause` property. The `failureType` property specifies
2560+
what the test was doing when the failure occurred.
2561+
25542562
<a id="ERR_TLS_CERT_ALTNAME_FORMAT"></a>
25552563

25562564
### `ERR_TLS_CERT_ALTNAME_FORMAT`

doc/api/index.md

+1
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
* [Report](report.md)
5555
* [Stream](stream.md)
5656
* [String decoder](string_decoder.md)
57+
* [Test runner](test_runner.md)
5758
* [Timers](timers.md)
5859
* [TLS/SSL](tls.md)
5960
* [Trace events](tracing.md)

doc/api/test_runner.md

+276
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,276 @@
1+
# Test runner
2+
3+
<!--introduced_in=REPLACEME-->
4+
5+
> Stability: 1 - Experimental
6+
7+
<!-- source_link=lib/test_runner.js -->
8+
9+
The `test_runner` module facilitates the creation of JavaScript tests that
10+
report results in [TAP][] format. To access it:
11+
12+
```mjs
13+
import test from 'test_runner';
14+
```
15+
16+
```cjs
17+
const test = require('test_runner');
18+
```
19+
20+
Tests created via the `test_runner` module consist of a single function that
21+
executes either synchronously or asynchronously. Synchronous tests are
22+
considered passing if they do not throw an exception. Asynchronous tests return
23+
a `Promise`, and are considered passing if the returned `Promise` does not
24+
reject. The following example illustrates how tests are written using the
25+
`test_runner` module.
26+
27+
```js
28+
test('synchronous passing test', (t) => {
29+
// This test passes because it does not throw an exception.
30+
assert.strictEqual(1, 1);
31+
});
32+
33+
test('synchronous failing test', (t) => {
34+
// This test fails because it throws an exception.
35+
assert.strictEqual(1, 2);
36+
});
37+
38+
test('asynchronous passing test', async (t) => {
39+
// This test passes because the Promise returned by the async
40+
// function is not rejected.
41+
assert.strictEqual(1, 1);
42+
});
43+
44+
test('asynchronous failing test', async (t) => {
45+
// This test fails because the Promise returned by the async
46+
// function is rejected.
47+
assert.strictEqual(1, 2);
48+
});
49+
50+
test('failing test using Promises', (t) => {
51+
// Promises can be used directly as well.
52+
return new Promise((resolve, reject) => {
53+
setImmediate(() => {
54+
reject(new Error('this will cause the test to fail'));
55+
});
56+
});
57+
});
58+
```
59+
60+
As a test file executes, TAP is written to the standard output of the Node.js
61+
process. This output can be interpreted by any test harness that understands
62+
the TAP format. If any tests fail, the process exit code is set to `1`.
63+
64+
## Subtests
65+
66+
The test context's `test()` method allows subtests to be created. This method
67+
behaves identically to the top level `test()` function. The following example
68+
demonstrates the creation of a top level test with two subtests.
69+
70+
```js
71+
test('top level test', async (t) => {
72+
await t.test('subtest 1', (t) => {
73+
assert.strictEqual(1, 1);
74+
});
75+
76+
await t.test('subtest 2', (t) => {
77+
assert.strictEqual(2, 2);
78+
});
79+
});
80+
```
81+
82+
In this example, `await` is used to ensure that both subtests have completed.
83+
This is necessary because parent tests do not wait for their subtests to
84+
complete. Any subtests that are still outstanding when their parent finishes
85+
are cancelled and treated as failures. Any subtest failures cause the parent
86+
test to fail.
87+
88+
## Skipping tests
89+
90+
Individual tests can be skipped by passing the `skip` option to the test, or by
91+
calling the test context's `skip()` method. Both of these options support
92+
including a message that is displayed in the TAP output as shown in the
93+
following example.
94+
95+
```js
96+
// The skip option is used, but no message is provided.
97+
test('skip option', { skip: true }, (t) => {
98+
// This code is never executed.
99+
});
100+
101+
// The skip option is used, and a message is provided.
102+
test('skip option with message', { skip: 'this is skipped' }, (t) => {
103+
// This code is never executed.
104+
});
105+
106+
test('skip() method', (t) => {
107+
// Make sure to return here as well if the test contains additional logic.
108+
t.skip();
109+
});
110+
111+
test('skip() method with message', (t) => {
112+
// Make sure to return here as well if the test contains additional logic.
113+
t.skip('this is skipped');
114+
});
115+
```
116+
117+
## Extraneous asynchronous activity
118+
119+
Once a test function finishes executing, the TAP results are output as quickly
120+
as possible while maintaining the order of the tests. However, it is possible
121+
for the test function to generate asynchronous activity that outlives the test
122+
itself. The test runner handles this type of activity, but does not delay the
123+
reporting of test results in order to accommodate it.
124+
125+
In the following example, a test completes with two `setImmediate()`
126+
operations still outstanding. The first `setImmediate()` attempts to create a
127+
new subtest. Because the parent test has already finished and output its
128+
results, the new subtest is immediately marked as failed, and reported in the
129+
top level of the file's TAP output.
130+
131+
The second `setImmediate()` creates an `uncaughtException` event.
132+
`uncaughtException` and `unhandledRejection` events originating from a completed
133+
test are handled by the `test_runner` module and reported as diagnostic
134+
warnings in the top level of the file's TAP output.
135+
136+
```js
137+
test('a test that creates asynchronous activity', (t) => {
138+
setImmediate(() => {
139+
t.test('subtest that is created too late', (t) => {
140+
throw new Error('error1');
141+
});
142+
});
143+
144+
setImmediate(() => {
145+
throw new Error('error2');
146+
});
147+
148+
// The test finishes after this line.
149+
});
150+
```
151+
152+
## `test([name][, options][, fn])`
153+
154+
<!-- YAML
155+
added: REPLACEME
156+
-->
157+
158+
* `name` {string} The name of the test, which is displayed when reporting test
159+
results. **Default:** The `name` property of `fn`, or `'<anonymous>'` if `fn`
160+
does not have a name.
161+
* `options` {Object} Configuration options for the test. The following
162+
properties are supported:
163+
* `concurrency` {number} The number of tests that can be run at the same time.
164+
If unspecified, subtests inherit this value from their parent.
165+
**Default:** `1`.
166+
* `skip` {boolean|string} If truthy, the test is skipped. If a string is
167+
provided, that string is displayed in the test results as the reason for
168+
skipping the test. **Default:** `false`.
169+
* `fn` {Function|AsyncFunction} The function under test. The test fails if this
170+
function throws an exception or returns a `Promise` that rejects. This
171+
function is invoked with a single [`TestContext`][] argument.
172+
**Default:** A no-op function.
173+
* Returns: {Promise} Resolved with `undefined` once the test completes.
174+
175+
The `test()` function is the value imported from the `test_runner` module. Each
176+
invocation of this function results in the creation of a test point in the TAP
177+
output.
178+
179+
The `TestContext` object passed to the `fn` argument can be used to perform
180+
actions related to the current test. Examples include skipping the test, adding
181+
additional TAP diagnostic information, or creating subtests.
182+
183+
`test()` returns a `Promise` that resolves once the test completes. The return
184+
value can usually be discarded for top level tests. However, the return value
185+
from subtests should be used to prevent the parent test from finishing first
186+
and cancelling the subtest as shown in the following example.
187+
188+
```js
189+
test('top level test', async (t) => {
190+
// The setTimeout() in the following subtest would cause it to outlive its
191+
// parent test if 'await' is removed on the next line. Once the parent test
192+
// completes, it will cancel any outstanding subtests.
193+
await t.test('longer running subtest', async (t) => {
194+
return new Promise((resolve, reject) => {
195+
setTimeout(resolve, 1000);
196+
});
197+
});
198+
});
199+
```
200+
201+
## Class: `TestContext`
202+
203+
<!-- YAML
204+
added: REPLACEME
205+
-->
206+
207+
An instance of `TestContext` is passed to each test function in order to
208+
interact with the test runner. However, the `TestContext` constructor is not
209+
exposed as part of the API.
210+
211+
### `context.diagnostic(message)`
212+
213+
<!-- YAML
214+
added: REPLACEME
215+
-->
216+
217+
* `message` {string} Message to be displayed as a TAP diagnostic.
218+
219+
This function is used to write TAP diagnostics to the output. Any diagnostic
220+
information is included at the end of the test's results. This function does
221+
not return a value.
222+
223+
### `context.skip([message])`
224+
225+
<!-- YAML
226+
added: REPLACEME
227+
-->
228+
229+
* `message` {string} Optional skip message to be displayed in TAP output.
230+
231+
This function causes the test's output to indicate the test as skipped. If
232+
`message` is provided, it is included in the TAP output. Calling `skip()` does
233+
not terminate execution of the test function. This function does not return a
234+
value.
235+
236+
### `context.todo([message])`
237+
238+
<!-- YAML
239+
added: REPLACEME
240+
-->
241+
242+
* `message` {string} Optional `TODO` message to be displayed in TAP output.
243+
244+
This function adds a `TODO` directive to the test's output. If `message` is
245+
provided, it is included in the TAP output. Calling `todo()` does not terminate
246+
execution of the test function. This function does not return a value.
247+
248+
### `context.test([name][, options][, fn])`
249+
250+
<!-- YAML
251+
added: REPLACEME
252+
-->
253+
254+
* `name` {string} The name of the subtest, which is displayed when reporting
255+
test results. **Default:** The `name` property of `fn`, or `'<anonymous>'` if
256+
`fn` does not have a name.
257+
* `options` {Object} Configuration options for the subtest. The following
258+
properties are supported:
259+
* `concurrency` {number} The number of tests that can be run at the same time.
260+
If unspecified, subtests inherit this value from their parent.
261+
**Default:** `1`.
262+
* `skip` {boolean|string} If truthy, the test is skipped. If a string is
263+
provided, that string is displayed in the test results as the reason for
264+
skipping the test. **Default:** `false`.
265+
* `fn` {Function|AsyncFunction} The function under test. The test fails if this
266+
function throws an exception or returns a `Promise` that rejects. This
267+
function is invoked with a single [`TestContext`][] argument.
268+
**Default:** A no-op function.
269+
* Returns: {Promise} Resolved with `undefined` once the test completes.
270+
271+
This function is used to create subtests under the current test. This function
272+
behaves in the same fashion as the top level [`test()`][] function.
273+
274+
[TAP]: https://testanything.org/
275+
[`TestContext`]: #class-testcontext
276+
[`test()`]: #testname-options-fn

lib/internal/errors.js

+12
Original file line numberDiff line numberDiff line change
@@ -1544,6 +1544,18 @@ E('ERR_STREAM_WRAP', 'Stream has StringDecoder set or is in objectMode', Error);
15441544
E('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error);
15451545
E('ERR_SYNTHETIC', 'JavaScript Callstack', Error);
15461546
E('ERR_SYSTEM_ERROR', 'A system error occurred', SystemError);
1547+
E('ERR_TEST_FAILURE', function(error, failureType) {
1548+
hideInternalStackFrames(this);
1549+
assert(typeof failureType === 'string',
1550+
"The 'failureType' argument must be of type string.");
1551+
1552+
const msg = error?.message ?? lazyInternalUtilInspect().inspect(error);
1553+
1554+
this.failureType = failureType;
1555+
this.cause = error;
1556+
1557+
return msg;
1558+
}, Error);
15471559
E('ERR_TLS_CERT_ALTNAME_FORMAT', 'Invalid subject alternative name string',
15481560
SyntaxError);
15491561
E('ERR_TLS_CERT_ALTNAME_INVALID', function(reason, host, cert) {

0 commit comments

Comments
 (0)