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

feat(learn): add section for dynamically generating test cases #7387

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions apps/site/pages/en/learn/test-runner/using-test-runner.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,40 @@ Then for each setup, create a dedicated `setup` file (ensuring the base `setup.m

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.

## Dynamically generating test cases

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`:

```js
import assert from 'node:assert/strict';
import { globSync } from 'node:fs';
import { test } from 'node:test';
import { fileURLToPath } from 'node:url';

test('Check package.jsons', { concurrency: true }, async t => {
const pjsons = await Promise.all(
globSync(
// Get all the package.json files 1-level deep within ./workspaces
// ⚠️ Passing a file URL string, like from import.meta.resolve, causes glob* to fail silently
fileURLToPath(import.meta.resolve('./workspaces/*/package.json'))
).map(path => import(path, { with: { type: 'json' } }))
);

const cases = pjsons.map(pjson =>
// ⚠️ `t.test`, NOT `test`
t.test(`Ensure fields are properly set: ${pjson.name}`, () => {
assert.partialDeepStrictEqual(pjson.keywords, [
'node.js',
'sliced bread',
]);
Comment on lines +89 to +92
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
assert.partialDeepStrictEqual(pjson.keywords, [
'node.js',
'sliced bread',
]);
assert.match(pjson.name, /@nodejs\/[a-z \-]+/);

})
);

// Allow the cases to run concurrently.
await Promise.allSettled(cases);
});
```

## ServiceWorker tests

[`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.
Expand Down
Loading