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

fix(web-worker): share mocker with main executor #6623

Merged
merged 6 commits into from
Oct 3, 2024
Merged
Show file tree
Hide file tree
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
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"`)
})