From fe7b8aeea641151f1db30f6ce7f0753680d16322 Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa Date: Thu, 3 Oct 2024 18:29:09 +0900 Subject: [PATCH] fix(web-worker): share mocker with main executor (#6623) --- packages/web-worker/src/runner.ts | 3 +++ test/core/src/web-worker/mock/worker-dep.ts | 3 +++ test/core/src/web-worker/mock/worker.ts | 3 +++ test/core/test/web-worker-mock.test.ts | 16 ++++++++++++++++ 4 files changed, 25 insertions(+) create mode 100644 test/core/src/web-worker/mock/worker-dep.ts create mode 100644 test/core/src/web-worker/mock/worker.ts create mode 100644 test/core/test/web-worker-mock.test.ts diff --git a/packages/web-worker/src/runner.ts b/packages/web-worker/src/runner.ts index 11d8fb628bb4..93ad8d2b2401 100644 --- a/packages/web-worker/src/runner.ts +++ b/packages/web-worker/src/runner.ts @@ -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) { diff --git a/test/core/src/web-worker/mock/worker-dep.ts b/test/core/src/web-worker/mock/worker-dep.ts new file mode 100644 index 000000000000..7bf5e2f34a39 --- /dev/null +++ b/test/core/src/web-worker/mock/worker-dep.ts @@ -0,0 +1,3 @@ +export function workerDep() { + return 'workerDep' +} diff --git a/test/core/src/web-worker/mock/worker.ts b/test/core/src/web-worker/mock/worker.ts new file mode 100644 index 000000000000..5239e5dfc23c --- /dev/null +++ b/test/core/src/web-worker/mock/worker.ts @@ -0,0 +1,3 @@ +import { workerDep } from './worker-dep' + +self.postMessage(workerDep()) diff --git a/test/core/test/web-worker-mock.test.ts b/test/core/test/web-worker-mock.test.ts new file mode 100644 index 000000000000..46c77d48497b --- /dev/null +++ b/test/core/test/web-worker-mock.test.ts @@ -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"`) +})