Skip to content

Commit f5caa8f

Browse files
authored
Document how to load multiple instances of the same "shared" worker
1 parent 843644b commit f5caa8f

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

docs/recipes/shared-workers.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,28 @@ const shared = registerSharedWorker({
3434

3535
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.
3636

37+
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:
38+
39+
```js
40+
import crypto from 'crypto';
41+
import {registerSharedWorker} from 'ava/plugin';
42+
43+
const key = Math.random() > 0.5 ? 'worker-a' : 'worker-b';
44+
45+
const shared = registerSharedWorker<any>({
46+
filename: new URL(
47+
`file:${path.resolve(
48+
__dirname,
49+
'worker.js'
50+
)}#${encodeURIComponent(key)}`
51+
),
52+
initialData: {workerKey: key},
53+
supportedProtocols: ['ava-4']
54+
});
55+
```
56+
57+
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.
58+
3759
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.
3860

3961
```js

0 commit comments

Comments
 (0)