Skip to content

Document how to load worker multiple times #3009

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

Merged
merged 2 commits into from
May 2, 2022
Merged
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
22 changes: 22 additions & 0 deletions docs/recipes/shared-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,28 @@ const shared = registerSharedWorker({

Within a test process you can only register one worker for each `filename`. Filenames are compared as-is, without normalization. If you call `registerSharedWorker()` a second time, the same worker instance is returned.

If for some reason you want to load the same file as multiple different workers, you can append a unique hash to the end of the filename:

```js
import crypto from 'crypto';
import {registerSharedWorker} from 'ava/plugin';

const key = Math.random() > 0.5 ? 'worker-a' : 'worker-b';

const shared = registerSharedWorker<any>({
filename: new URL(
`file:${path.resolve(
__dirname,
'worker.js'
)}#${encodeURIComponent(key)}`
),
initialData: {workerKey: key},
supportedProtocols: ['ava-4']
});
```

This works because the `filename` parameter accepts [URL](https://nodejs.org/api/url.html) objects, meaning you could use a query component for the key instead if you wanted.

You can supply a `teardown()` function which will be called after all tests have finished. If you call `registerSharedWorker()` multiple times then the `teardown()` function will be invoked for each registration, even though you only got one worker instance. The most recently registered `teardown()` function is called first, and so forth. `teardown()` functions execute sequentially.

```js
Expand Down