Skip to content

Commit 20f1c31

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 6a51306 commit 20f1c31

14 files changed

+1589
-0
lines changed

doc/api/errors.md

Lines changed: 8 additions & 0 deletions
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

Lines changed: 1 addition & 0 deletions
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

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

lib/internal/errors.js

Lines changed: 12 additions & 0 deletions
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)