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(browser): correctly import optimized module in vi.importActual #6219

Merged
merged 2 commits into from
Jul 25, 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
13 changes: 10 additions & 3 deletions packages/browser/src/client/tester/mocker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,19 @@ export class VitestBrowserClientMocker {
)
}
const ext = extname(resolved.id)
const url = new URL(`/@id/${resolved.id}`, location.href)
const query = `_vitest_original&ext.${ext}`
const url = new URL(resolved.url, location.href)
const query = `_vitest_original&ext${ext}`
const actualUrl = `${url.pathname}${
url.search ? `${url.search}&${query}` : `?${query}`
}${url.hash}`
return getBrowserState().wrapModule(() => import(/* @vite-ignore */ actualUrl))
return getBrowserState().wrapModule(() => import(/* @vite-ignore */ actualUrl)).then((mod) => {
if (!resolved.optimized || typeof mod.default === 'undefined') {
return mod
}
// vite injects this helper for optimized modules, so we try to follow the same behavior
const m = mod.default
return m?.__esModule ? m : { ...((typeof m === 'object' && !Array.isArray(m)) || typeof m === 'function' ? m : {}), default: m }
})
}

public async importMock(rawId: string, importer: string) {
Expand Down
47 changes: 43 additions & 4 deletions packages/browser/src/node/rpc.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { existsSync, promises as fs } from 'node:fs'
import { dirname } from 'pathe'
import { dirname, isAbsolute, join } from 'pathe'
import { createBirpc } from 'birpc'
import { parse, stringify } from 'flatted'
import type { WebSocket } from 'ws'
Expand All @@ -8,11 +8,12 @@ import type { BrowserCommandContext } from 'vitest/node'
import { createDebugger, isFileServingAllowed } from 'vitest/node'
import type { WebSocketBrowserEvents, WebSocketBrowserHandlers } from './types'
import type { BrowserServer } from './server'
import { resolveMock } from './resolveMock'
import { cleanUrl, resolveMock } from './resolveMock'

const debug = createDebugger('vitest:browser:api')

const BROWSER_API_PATH = '/__vitest_browser_api__'
const VALID_ID_PREFIX = '/@id/'

export function setupBrowserRpc(
server: BrowserServer,
Expand Down Expand Up @@ -118,14 +119,44 @@ export function setupBrowserRpc(
ctx.cancelCurrentRun(reason)
},
async resolveId(id, importer) {
const result = await project.server.pluginContainer.resolveId(
const resolved = await vite.pluginContainer.resolveId(
id,
importer,
{
ssr: false,
},
)
return result
if (!resolved) {
return null
}
const isOptimized = resolved.id.startsWith(withTrailingSlash(vite.config.cacheDir))
let url: string
// normalise the URL to be acceptible by the browser
// https://github.com/vitejs/vite/blob/e833edf026d495609558fd4fb471cf46809dc369/packages/vite/src/node/plugins/importAnalysis.ts#L335
const root = vite.config.root
if (resolved.id.startsWith(withTrailingSlash(root))) {
url = resolved.id.slice(root.length)
}
else if (
resolved.id !== '/@react-refresh'
&& isAbsolute(resolved.id)
&& existsSync(cleanUrl(resolved.id))
) {
url = join('/@fs/', resolved.id)
}
else {
url = resolved.id
}
if (url[0] !== '.' && url[0] !== '/') {
url = id.startsWith(VALID_ID_PREFIX)
? id
: VALID_ID_PREFIX + id.replace('\0', '__x00__')
}
return {
id: resolved.id,
url,
optimized: isOptimized,
}
},
debug(...args) {
ctx.logger.console.debug(...args)
Expand Down Expand Up @@ -242,3 +273,11 @@ export function stringifyReplace(key: string, value: any) {
return value
}
}

function withTrailingSlash(path: string): string {
if (path[path.length - 1] !== '/') {
return `${path}/`
}

return path
}
2 changes: 1 addition & 1 deletion packages/browser/src/node/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export interface WebSocketBrowserHandlers {
resolveId: (
id: string,
importer?: string
) => Promise<{ id: string } | null>
) => Promise<{ id: string; url: string; optimized: boolean } | null>
triggerCommand: <T>(
contextId: string,
command: string,
Expand Down
14 changes: 14 additions & 0 deletions test/browser/fixtures/mocking/import-actual-dep.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { a, b } from '@vitest/cjs-lib'
import { expect, test, vi } from 'vitest'

vi.mock(import('@vitest/cjs-lib'), async (importOriginal) => {
const original = await importOriginal()
return {
...await importOriginal(),
}
})

test('mocking works correctly', () => {
expect(a).toBe('a')
expect(b).toBe('b')
})
1 change: 1 addition & 0 deletions test/browser/specs/mocking.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
console.error(result.stderr)
})

expect(result.stderr).toBe('')

Check failure on line 15 in test/browser/specs/mocking.test.ts

View workflow job for this annotation

GitHub Actions / test-browser (edge, webkit)

specs/mocking.test.ts > mocking works correctly - isolated true

AssertionError: expected '\n⎯⎯⎯⎯⎯⎯ Unhandled Error ⎯⎯⎯⎯⎯⎯⎯\nErr…' to be '' // Object.is equality - Expected + Received + + ⎯⎯⎯⎯⎯⎯ Unhandled Error ⎯⎯⎯⎯⎯⎯⎯ + Error: End of central directory not found + ❯ ZipReader.getEntriesGenerator ../../../../node_modules/.pnpm/@[email protected]/node_modules/@zip.js/zip.js/lib/core/zip-reader.js:160:11 + ❯ processTicksAndRejections ../../node:internal/process/task_queues:95:5 + ❯ ZipReader.getEntries ../../../../node_modules/.pnpm/@[email protected]/node_modules/@zip.js/zip.js/lib/core/zip-reader.js:324:20 + ❯ downloadZip ../../../../node_modules/.pnpm/[email protected]/node_modules/edgedriver/src/install.ts:164:23 + ❯ download ../../../../node_modules/.pnpm/[email protected]/node_modules/edgedriver/src/install.ts:53:3 + ❯ start ../../../../node_modules/.pnpm/[email protected]/node_modules/edgedriver/src/index.ts:13:22 + ❯ startWebDriver ../../../../node_modules/.pnpm/@wdio[email protected]/node_modules/@wdio/utils/build/node/startWebDriver.js:108:25 + ❯ Function.newSession ../../../../node_modules/.pnpm/[email protected]/node_modules/webdriver/build/index.js:17:31 + ❯ remote ../../../../node_modules/.pnpm/[email protected][email protected]/node_modules/webdriverio/build/index.js:46:22 + ❯ WebdriverBrowserProvider.openBrowser ../../../../packages/browser/dist/webdriver-BdVqnfdE.js:201:20 + ❯ WebdriverBrowserProvider.openPage ../../../../packages/browser/dist/webdriver-BdVqnfdE.js:238:29 + ❯ executeTests ../../../../packages/browser/dist/index.js:2454:5 + ❯ runWorkspaceTests ../../../../packages/browser/dist/index.js:2471:7 + ❯ executeTests ../../../../packages/vitest/dist/chunks/cli-api.BrGy2RRj.js:9367:5 + + + ❯ specs/mocking.test.ts:15:25

Check failure on line 15 in test/browser/specs/mocking.test.ts

View workflow job for this annotation

GitHub Actions / test-browser (edge, webkit)

specs/mocking.test.ts > mocking works correctly - isolated false

AssertionError: expected '\n⎯⎯⎯⎯⎯⎯ Unhandled Error ⎯⎯⎯⎯⎯⎯⎯\nErr…' to be '' // Object.is equality - Expected + Received + + ⎯⎯⎯⎯⎯⎯ Unhandled Error ⎯⎯⎯⎯⎯⎯⎯ + Error: End of central directory not found + ❯ ZipReader.getEntriesGenerator ../../../../node_modules/.pnpm/@[email protected]/node_modules/@zip.js/zip.js/lib/core/zip-reader.js:160:11 + ❯ processTicksAndRejections ../../node:internal/process/task_queues:95:5 + ❯ ZipReader.getEntries ../../../../node_modules/.pnpm/@[email protected]/node_modules/@zip.js/zip.js/lib/core/zip-reader.js:324:20 + ❯ downloadZip ../../../../node_modules/.pnpm/[email protected]/node_modules/edgedriver/src/install.ts:164:23 + ❯ download ../../../../node_modules/.pnpm/[email protected]/node_modules/edgedriver/src/install.ts:53:3 + ❯ start ../../../../node_modules/.pnpm/[email protected]/node_modules/edgedriver/src/index.ts:13:22 + ❯ startWebDriver ../../../../node_modules/.pnpm/@wdio[email protected]/node_modules/@wdio/utils/build/node/startWebDriver.js:108:25 + ❯ Function.newSession ../../../../node_modules/.pnpm/[email protected]/node_modules/webdriver/build/index.js:17:31 + ❯ remote ../../../../node_modules/.pnpm/[email protected][email protected]/node_modules/webdriverio/build/index.js:46:22 + ❯ WebdriverBrowserProvider.openBrowser ../../../../packages/browser/dist/webdriver-BdVqnfdE.js:201:20 + ❯ WebdriverBrowserProvider.openPage ../../../../packages/browser/dist/webdriver-BdVqnfdE.js:238:29 + ❯ executeTests ../../../../packages/browser/dist/index.js:2454:5 + ❯ runWorkspaceTests ../../../../packages/browser/dist/index.js:2471:7 + ❯ executeTests ../../../../packages/vitest/dist/chunks/cli-api.BrGy2RRj.js:9367:5 + + + ❯ specs/mocking.test.ts:15:25
expect(result.stdout).toContain('automocked.test.ts')
expect(result.stdout).toContain('mocked-__mocks__.test.ts')
expect(result.stdout).toContain('mocked-factory.test.ts')
Expand All @@ -24,6 +24,7 @@
expect(result.stdout).toContain('import-actual-query.test.ts')
expect(result.stdout).toContain('import-mock.test.ts')
expect(result.stdout).toContain('mocked-do-mock-factory.test.ts')
expect(result.stdout).toContain('import-actual-dep.test.ts')
expect(result.exitCode).toBe(0)
})

Expand All @@ -37,7 +38,7 @@
await ctx.closingPromise
})

await vitest.waitForStdout('Waiting for file changes...')

Check failure on line 41 in test/browser/specs/mocking.test.ts

View workflow job for this annotation

GitHub Actions / test-browser (edge, webkit)

specs/mocking.test.ts > mocking dependency correctly invalidates it on rerun

Error: Timeout when waiting for error "Waiting for file changes...". Received: DEV v2.0.4 /home/runner/work/vitest/vitest/test/browser/fixtures/mocking-watch Browser runner started at http://localhost:5173/ ⎯⎯⎯⎯⎯⎯ Unhandled Errors ⎯⎯⎯⎯⎯⎯ Vitest caught 1 unhandled error during the test run. This might cause false positive tests. Resolve unhandled errors to make sure your tests are not affected. ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Test Files no tests Tests no tests Errors 1 error Start at 10:59:43 Duration 581ms (transform 0ms, setup 0ms, collect 0ms, tests 0ms, environment 0ms, prepare 0ms) FAIL Tests failed. Watching for file changes... press h to show help, press q to quit ❯ specs/mocking.test.ts:41:16

expect(vitest.stderr).toBe('')
expect(vitest.stdout).toContain('1_mocked-on-watch-change.test.ts')
Expand Down
Loading