Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: dynamically generating tests with top-level await and ESM test files #4617

Merged
merged 1 commit into from
Apr 3, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
juergba marked this conversation as resolved.
Show resolved Hide resolved
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