Skip to content

Commit 670dda7

Browse files
mucsi96kettanaito
andauthoredNov 7, 2022
feat: do not interfere with shared workers (#1448)
* feat: add support for shared workers * test: touch-up shared worker test * test: rename the shared worker test Co-authored-by: Artem Zakharchenko <kettanaito@gmail.com>
1 parent 41798eb commit 670dda7

File tree

4 files changed

+46
-1
lines changed

4 files changed

+46
-1
lines changed
 

‎src/mockServiceWorker.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ async function handleRequest(event, requestId) {
174174
async function resolveMainClient(event) {
175175
const client = await self.clients.get(event.clientId)
176176

177-
if (client.frameType === 'top-level') {
177+
if (client?.frameType === 'top-level') {
178178
return client
179179
}
180180

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import { setupWorker } from 'msw'
2+
3+
const worker = setupWorker()
4+
5+
worker.start()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import * as path from 'path'
2+
import { pageWith } from 'page-with'
3+
import { waitFor } from '../../../../support/waitFor'
4+
5+
function createRuntime() {
6+
return pageWith({
7+
example: path.resolve(__dirname, 'shared-worker.mocks.ts'),
8+
contentBase: path.resolve(__dirname),
9+
})
10+
}
11+
12+
test('does not interfere with a shared worker', async () => {
13+
const { page, consoleSpy } = await createRuntime()
14+
15+
await page.evaluate(() => {
16+
const worker = new SharedWorker('/worker.js')
17+
18+
worker.addEventListener('error', () =>
19+
console.error('There is an error with worker'),
20+
)
21+
22+
worker.port.onmessage = (event) => {
23+
console.log(event.data)
24+
}
25+
26+
worker.port.postMessage('john')
27+
})
28+
29+
await waitFor(() => {
30+
expect(consoleSpy.get('error')).toBeUndefined()
31+
expect(consoleSpy.get('log')).toContain('hello, john')
32+
})
33+
})
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
onconnect = (event) => {
2+
const port = event.ports[0]
3+
4+
port.onmessage = (event) => {
5+
port.postMessage(`hello, ${event.data}`)
6+
}
7+
}

0 commit comments

Comments
 (0)
Please sign in to comment.