Skip to content

Commit

Permalink
fix(web-worker): share mocker with main executor (#6623)
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa authored Oct 3, 2024
1 parent d289e7e commit fe7b8ae
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 0 deletions.
3 changes: 3 additions & 0 deletions packages/web-worker/src/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import { VitestExecutor } from 'vitest/execute'

export class InlineWorkerRunner extends VitestExecutor {
constructor(options: any, private context: any) {
// share the same mocker as main executor
const mocker = (globalThis as any).__vitest_mocker__
super(options)
this.mocker = (globalThis as any).__vitest_mocker__ = mocker
}

prepareContext(context: Record<string, any>) {
Expand Down
3 changes: 3 additions & 0 deletions test/core/src/web-worker/mock/worker-dep.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function workerDep() {
return 'workerDep'
}
3 changes: 3 additions & 0 deletions test/core/src/web-worker/mock/worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { workerDep } from './worker-dep'

self.postMessage(workerDep())
16 changes: 16 additions & 0 deletions test/core/test/web-worker-mock.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import '@vitest/web-worker'
import { expect, test, vi } from 'vitest'
import { workerDep } from '../src/web-worker/mock/worker-dep'

vi.mock(import('../src/web-worker/mock/worker-dep'), () => ({ workerDep: () => 'mocked' }))

test('mock', async () => {
expect(workerDep()).toMatchInlineSnapshot(`"mocked"`)
const worker = new Worker(new URL('../src/web-worker/mock/worker', import.meta.url))
const data = await new Promise((resolve) => {
worker.addEventListener('message', (e) => {
resolve(e.data)
})
})
expect(data).toMatchInlineSnapshot(`"mocked"`)
})

0 comments on commit fe7b8ae

Please sign in to comment.