Skip to content

Commit

Permalink
docs: dynamic tests with top-level await [ci skip]
Browse files Browse the repository at this point in the history
  • Loading branch information
juergba committed Apr 2, 2021
1 parent d7ed5c2 commit 43739a6
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 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,32 @@ 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
// 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);
});

describe('add()', function() {
// NO, don't use asynchronous callbacks
tests.forEach(({args, expected}) => {
it(`correctly adds ${args.length} args`, function() {
const res = add(args);
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 43739a6

Please sign in to comment.