Skip to content

Commit 8a2da76

Browse files
authoredApr 3, 2021
docs: dynamic tests with top-level await (#4617) [ci skip]
1 parent d7ed5c2 commit 8a2da76

File tree

1 file changed

+31
-3
lines changed

1 file changed

+31
-3
lines changed
 

‎docs/index.md

+31-3
Original file line numberDiff line numberDiff line change
@@ -684,7 +684,7 @@ Given Mocha's use of function expressions to define suites and test cases, it's
684684
Take the following example:
685685

686686
```js
687-
const assert = require('chai').assert;
687+
const assert = require('assert');
688688

689689
function add(args) {
690690
return args.reduce((prev, curr) => prev + curr, 0);
@@ -700,7 +700,7 @@ describe('add()', function() {
700700
tests.forEach(({args, expected}) => {
701701
it(`correctly adds ${args.length} args`, function() {
702702
const res = add(args);
703-
assert.equal(res, expected);
703+
assert.strictEqual(res, expected);
704704
});
705705
});
706706
});
@@ -725,7 +725,7 @@ describe('add()', function() {
725725
const testAdd = ({args, expected}) =>
726726
function() {
727727
const res = add(args);
728-
assert.equal(res, expected);
728+
assert.strictEqual(res, expected);
729729
};
730730

731731
it('correctly adds 2 args', testAdd({args: [1, 2], expected: 3}));
@@ -734,6 +734,34 @@ describe('add()', function() {
734734
});
735735
```
736736

737+
With `top-level await` you can collect your test data in a dynamic and asynchronous way while the test file is being loaded:
738+
739+
```js
740+
// testfile.mjs
741+
import assert from 'assert';
742+
743+
// top-level await: Node >= v14.8.0 with ESM test file
744+
const tests = await new Promise(resolve => {
745+
setTimeout(() => {
746+
resolve([
747+
{args: [1, 2], expected: 3},
748+
{args: [1, 2, 3], expected: 6},
749+
{args: [1, 2, 3, 4], expected: 10}
750+
]);
751+
}, 5000);
752+
});
753+
754+
// in suites ASYNCHRONOUS callbacks are NOT supported
755+
describe('add()', function() {
756+
tests.forEach(({args, expected}) => {
757+
it(`correctly adds ${args.length} args`, function() {
758+
const res = args.reduce((sum, curr) => sum + curr, 0);
759+
assert.strictEqual(res, expected);
760+
});
761+
});
762+
});
763+
```
764+
737765
<h2 id="test-duration">Test duration</h2>
738766

739767
Many reporters will display test duration and flag tests that are slow (default: 75ms), as shown here with the SPEC reporter:

0 commit comments

Comments
 (0)