Skip to content

Commit

Permalink
Merge branch 'fix-vitest-dev#4686' into main-mbland
Browse files Browse the repository at this point in the history
  • Loading branch information
mbland committed Dec 8, 2023
2 parents 64b9bbd + 810b49c commit f9bbec5
Show file tree
Hide file tree
Showing 9 changed files with 79 additions and 40 deletions.
4 changes: 2 additions & 2 deletions packages/browser/src/client/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { importId } from './utils'

const { Date, console } = globalThis

export async function setupConsoleLogSpy() {
const { stringify, format, inspect } = await importId('vitest/utils') as typeof import('vitest/utils')
export async function setupConsoleLogSpy(basePath: string) {
const { stringify, format, inspect } = await importId('vitest/utils', basePath) as typeof import('vitest/utils')
const { log, info, error, dir, dirxml, trace, time, timeEnd, timeLog, warn, debug, count, countReset } = console
const formatInput = (input: unknown) => {
if (input instanceof Node)
Expand Down
13 changes: 8 additions & 5 deletions packages/browser/src/client/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { ResolvedConfig } from 'vitest'
import type { CancelReason, VitestRunner } from '@vitest/runner'
import type { VitestExecutor } from '../../../vitest/src/runtime/execute'
import { createBrowserRunner } from './runner'
import { importId } from './utils'
import { importId as importIdImpl } from './utils'
import { setupConsoleLogSpy } from './logger'
import { createSafeRpc, rpc, rpcDone } from './rpc'
import { setupDialogsSpy } from './dialog'
Expand All @@ -24,6 +24,10 @@ const url = new URL(location.href)
const testId = url.searchParams.get('id') || 'unknown'
const reloadTries = Number(url.searchParams.get('reloadTries') || '0')

const basePath = () => config!.base! || '/'
const importId = (id: string) => importIdImpl(id, basePath())
const viteClientPath = () => `${basePath()}@vite/client`

function getQueryPaths() {
return url.searchParams.getAll('path')
}
Expand Down Expand Up @@ -181,15 +185,14 @@ ws.addEventListener('open', async () => {
const iFrame = document.getElementById('vitest-ui') as HTMLIFrameElement
iFrame.setAttribute('src', '/__vitest__/')

await setupConsoleLogSpy()
await setupConsoleLogSpy(basePath())
setupDialogsSpy()
await runTests(paths, config!)
})

async function prepareTestEnvironment(config: ResolvedConfig) {
// need to import it before any other import, otherwise Vite optimizer will hang
const viteClientPath = '/@vite/client'
await import(viteClientPath)
await import(viteClientPath())

const {
startTests,
Expand All @@ -204,7 +207,7 @@ async function prepareTestEnvironment(config: ResolvedConfig) {

if (!runner) {
const { VitestTestRunner } = await importId('vitest/runners') as typeof import('vitest/runners')
const BrowserRunner = createBrowserRunner(VitestTestRunner, { takeCoverage: () => takeCoverageInsideWorker(config.coverage, executor) })
const BrowserRunner = createBrowserRunner(VitestTestRunner, { takeCoverage: () => takeCoverageInsideWorker(config.coverage, executor) }, basePath())
runner = new BrowserRunner({ config, browserHashMap })
}

Expand Down
7 changes: 4 additions & 3 deletions packages/browser/src/client/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ interface CoverageHandler {
export function createBrowserRunner(
original: { new(config: ResolvedConfig): VitestRunner },
coverageModule: CoverageHandler | null,
basePath: string,
): { new(options: BrowserRunnerOptions): VitestRunner } {
return class BrowserTestRunner extends original {
public config: ResolvedConfig
Expand Down Expand Up @@ -71,9 +72,9 @@ export function createBrowserRunner(
}

// on Windows we need the unit to resolve the test file
const importpath = /^\w:/.test(filepath)
? `/@fs/${filepath}?${test ? 'browserv' : 'v'}=${hash}`
: `${filepath}?${test ? 'browserv' : 'v'}=${hash}`
const prefix = `${basePath}${/^\w:/.test(filepath) ? '@fs/' : ''}`
const query = `${test ? 'browserv' : 'v'}=${hash}`
const importpath = `${prefix}${filepath}?${query}`.replace(/\/+/g, '/')
await import(importpath)
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/browser/src/client/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export async function importId(id: string) {
const name = `/@id/${id}`
export async function importId(id: string, basePath: string) {
const name = `${basePath}@id/${id}`
// @ts-expect-error mocking vitest apis
return __vi_wrap_module__(import(name))
}
6 changes: 3 additions & 3 deletions test/browser/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
"private": true,
"scripts": {
"test": "pnpm run test:webdriverio && pnpm run test:playwright",
"test:webdriverio": "PROVIDER=webdriverio node --test specs/",
"test:playwright": "PROVIDER=playwright node --test specs/",
"test:safaridriver": "PROVIDER=webdriverio BROWSER=safari node --test specs/",
"test:webdriverio": "PROVIDER=webdriverio node --test --test-concurrency=1 specs/",
"test:playwright": "PROVIDER=playwright node --test --test-concurrency=1 specs/",
"test:safaridriver": "PROVIDER=webdriverio BROWSER=safari node --test --test-concurrency=1 specs/",
"coverage": "vitest --coverage.enabled --coverage.provider=istanbul --browser.headless=yes"
},
"devDependencies": {
Expand Down
18 changes: 18 additions & 0 deletions test/browser/specs/fix-4686.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import assert from 'node:assert'
import test from 'node:test'
import runVitest from './run-vitest.mjs'

const {
stderr,
browserResultJson,
passedTests,
failedTests,
} = await runVitest(['--config', 'vitest.config-basepath.mts'])

await test('tests run in presence of config.base', async () => {
assert.ok(browserResultJson.testResults.length === 8, 'Not all the tests have been run')
assert.ok(passedTests.length === 7, 'Some tests failed')
assert.ok(failedTests.length === 1, 'Some tests have passed but should fail')

assert.doesNotMatch(stderr, /Unhandled Error/, 'doesn\'t have any unhandled errors')
})
30 changes: 30 additions & 0 deletions test/browser/specs/run-vitest.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { readFile } from 'node:fs/promises'
import { execa } from 'execa'

const browser = process.env.BROWSER || (process.env.PROVIDER === 'playwright' ? 'chromium' : 'chrome')

export default async function runVitest(moreArgs = []) {
const argv = ['vitest', '--run', `--browser.name=${browser}`]

if (browser !== 'safari')
argv.push('--browser.headless')

const { stderr, stdout } = await execa('npx', argv.concat(moreArgs), {
env: {
...process.env,
CI: 'true',
NO_COLOR: 'true',
},
reject: false,
})
const browserResult = await readFile('./browser.json', 'utf-8')
const browserResultJson = JSON.parse(browserResult)

const getPassed = results => results.filter(result => result.status === 'passed')
const getFailed = results => results.filter(result => result.status === 'failed')

const passedTests = getPassed(browserResultJson.testResults)
const failedTests = getFailed(browserResultJson.testResults)

return { stderr, stdout, browserResultJson, passedTests, failedTests }
}
33 changes: 8 additions & 25 deletions test/browser/specs/runner.test.mjs
Original file line number Diff line number Diff line change
@@ -1,31 +1,14 @@
import assert from 'node:assert'
import { readFile } from 'node:fs/promises'
import test from 'node:test'
import { execa } from 'execa'
import runVitest from './run-vitest.mjs'

const browser = process.env.BROWSER || (process.env.PROVIDER === 'playwright' ? 'chromium' : 'chrome')
const argv = ['vitest', '--run', `--browser.name=${browser}`]

if (browser !== 'safari')
argv.push('--browser.headless')

const { stderr, stdout } = await execa('npx', argv, {
env: {
...process.env,
CI: 'true',
NO_COLOR: 'true',
},
reject: false,
})

const browserResult = await readFile('./browser.json', 'utf-8')
const browserResultJson = JSON.parse(browserResult)

const getPassed = results => results.filter(result => result.status === 'passed')
const getFailed = results => results.filter(result => result.status === 'failed')

const passedTests = getPassed(browserResultJson.testResults)
const failedTests = getFailed(browserResultJson.testResults)
const {
stderr,
stdout,
browserResultJson,
passedTests,
failedTests,
} = await runVitest()

await test('tests are actually running', async () => {
assert.ok(browserResultJson.testResults.length === 8, 'Not all the tests have been run')
Expand Down
4 changes: 4 additions & 0 deletions test/browser/vitest.config-basepath.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { defineConfig, mergeConfig } from 'vitest/config'
import baseConfig from './vitest.config.mts'

export default mergeConfig(baseConfig, defineConfig({ base: '/fix-4686' }))

0 comments on commit f9bbec5

Please sign in to comment.