Skip to content

Commit

Permalink
docs: dynamic tests with top-level await (#4617) [ci skip]
Browse files Browse the repository at this point in the history
  • Loading branch information
juergba committed Apr 3, 2021
1 parent d7ed5c2 commit 8a2da76
Showing 1 changed file with 31 additions and 3 deletions.
34 changes: 31 additions & 3 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -684,7 +684,7 @@ Given Mocha's use of function expressions to define suites and test cases, it's
Take the following example:

```js
const assert = require('chai').assert;
const assert = require('assert');

function add(args) {
return args.reduce((prev, curr) => prev + curr, 0);
Expand All @@ -700,7 +700,7 @@ describe('add()', function() {
tests.forEach(({args, expected}) => {
it(`correctly adds ${args.length} args`, function() {
const res = add(args);
assert.equal(res, expected);
assert.strictEqual(res, expected);
});
});
});
Expand All @@ -725,7 +725,7 @@ describe('add()', function() {
const testAdd = ({args, expected}) =>
function() {
const res = add(args);
assert.equal(res, expected);
assert.strictEqual(res, expected);
};

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

With `top-level await` you can collect your test data in a dynamic and asynchronous way while the test file is being loaded:

```js
// testfile.mjs
import assert from 'assert';

// top-level await: Node >= v14.8.0 with ESM test file
const tests = await new Promise(resolve => {
setTimeout(() => {
resolve([
{args: [1, 2], expected: 3},
{args: [1, 2, 3], expected: 6},
{args: [1, 2, 3, 4], expected: 10}
]);
}, 5000);
});

// in suites ASYNCHRONOUS callbacks are NOT supported
describe('add()', function() {
tests.forEach(({args, expected}) => {
it(`correctly adds ${args.length} args`, function() {
const res = args.reduce((sum, curr) => sum + curr, 0);
assert.strictEqual(res, expected);
});
});
});
```

<h2 id="test-duration">Test duration</h2>

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

0 comments on commit 8a2da76

Please sign in to comment.