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): handle config.base (#4686) #4692

Merged
merged 4 commits into from
Jan 4, 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
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
11 changes: 7 additions & 4 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 _importId } 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) => _importId(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 Down
11 changes: 6 additions & 5 deletions packages/browser/src/client/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ interface CoverageHandler {
}

export function createBrowserRunner(
original: { new(config: ResolvedConfig): VitestRunner },
VitestRunner: { new(config: ResolvedConfig): VitestRunner },
coverageModule: CoverageHandler | null,
): { new(options: BrowserRunnerOptions): VitestRunner } {
return class BrowserTestRunner extends original {
return class BrowserTestRunner extends VitestRunner {
public config: ResolvedConfig
hashMap = new Map<string, [test: boolean, timstamp: string]>()

Expand Down Expand Up @@ -69,11 +69,12 @@ export function createBrowserRunner(
hash = Date.now().toString()
this.hashMap.set(filepath, [false, hash])
}
const base = this.config.base || '/'

// 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 = `${base}${/^\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
20 changes: 20 additions & 0 deletions test/browser/specs/fix-4686.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// fix #4686

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', 'basic.test.ts'])

await test('tests run in presence of config.base', async () => {
assert.ok(browserResultJson.testResults.length === 1, 'Not all the tests have been run')
assert.ok(passedTests.length === 1, 'Some tests failed')
assert.ok(failedTests.length === 0, '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 === 10, '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.mjs'

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