Skip to content

Commit 8d5a891

Browse files
feat(learn): add section for dynamically generating test cases
1 parent baae0f1 commit 8d5a891

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

apps/site/pages/en/learn/test-runner/using-test-runner.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,40 @@ Then for each setup, create a dedicated `setup` file (ensuring the base `setup.m
6464

6565
Each example below was taken from real-world projects; they may not be appropriate/applicable to yours, but each demonstrate general concepts that are broadly applicable.
6666

67+
## Dynamically generating test cases
68+
69+
Some times, you may want to dynamically generate test-cases. For instance, you want to test the same thing across a bunch of files. This is possible, albeit slightly arcane. You must use `test` (you cannot use `describe`) + `await testContext.test`:
70+
71+
```js
72+
import assert from 'node:assert/strict';
73+
import { globSync } from 'node:fs';
74+
import { test } from 'node:test';
75+
import { fileURLToPath } from 'node:url';
76+
77+
test('Check package.jsons', { concurrency: true }, async t => {
78+
const pjsons = await Promise.all(
79+
globSync(
80+
// Get all the package.json files 1-level deep within ./workspaces
81+
// ⚠️ Passing a file URL string, like from import.meta.resolve, causes glob* to fail silently
82+
fileURLToPath(import.meta.resolve('./workspaces/*/package.json'))
83+
).map(path => import(path, { with: { type: 'json' } }))
84+
);
85+
86+
// ⚠️ `t.test`, NOT `test`
87+
const cases = pjsons.map(pjson =>
88+
t.test(`Ensure fields are properly set: ${pjson.name}`, () => {
89+
assert.partialDeepStrictEqual(pjson.keywords, [
90+
'node.js',
91+
'sliced bread',
92+
]);
93+
})
94+
);
95+
96+
// Allow the cases to run concurrently.
97+
await Promise.allSettled(cases);
98+
});
99+
```
100+
67101
## ServiceWorker tests
68102
69103
[`ServiceWorkerGlobalScope`](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) contains very specific APIs that don't exist in other environments, and some of its APIs are seemingly similar to others (ex `fetch`) but have augmented behaviour. You do not want these to spill into unrelated tests.

0 commit comments

Comments
 (0)