From 8a2da76001142005826e544e4fb702ae2a77797f Mon Sep 17 00:00:00 2001 From: Juerg B <44573692+juergba@users.noreply.github.com> Date: Sat, 3 Apr 2021 15:05:17 +0200 Subject: [PATCH] docs: dynamic tests with top-level await (#4617) [ci skip] --- docs/index.md | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/docs/index.md b/docs/index.md index 32ee71258c..b0d31b4e7b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -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); @@ -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); }); }); }); @@ -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})); @@ -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); + }); + }); +}); +``` +

Test duration

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