Skip to content

Commit

Permalink
Merge branch 'main' into fix/test-extend/hooks-top-level
Browse files Browse the repository at this point in the history
  • Loading branch information
Dunqing committed Sep 8, 2023
2 parents 781d0e3 + 91853bb commit 8250c56
Show file tree
Hide file tree
Showing 29 changed files with 67 additions and 41 deletions.
4 changes: 2 additions & 2 deletions docs/guide/index.md
Expand Up @@ -71,7 +71,7 @@ Next, in order to execute the test, add the following section to your `package.j

Finally, run `npm run test`, `yarn test`, or `pnpm test`, depending on your package manager, and Vitest will print this message:

```log
```txt
✓ sum.test.js (1)
✓ adds 1 + 2 to equal 3
Expand Down Expand Up @@ -111,7 +111,7 @@ Even if you do not use Vite yourself, Vitest relies heavily on it for its transf

If you are already using Vite, add `test` property in your Vite config. You'll also need to add a reference to Vitest types using a [triple slash directive](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html#-reference-types-) at the top of your config file.

```ts
```ts
/// <reference types="vitest" />
import { defineConfig } from 'vite'

Expand Down
2 changes: 1 addition & 1 deletion package.json
@@ -1,7 +1,7 @@
{
"name": "@vitest/monorepo",
"type": "module",
"version": "0.34.3",
"version": "0.34.4",
"private": true,
"packageManager": "pnpm@8.7.4",
"description": "A blazing fast unit test framework powered by Vite",
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/package.json
@@ -1,7 +1,7 @@
{
"name": "@vitest/browser",
"type": "module",
"version": "0.34.3",
"version": "0.34.4",
"description": "Browser running for Vitest",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
Expand Down
2 changes: 1 addition & 1 deletion packages/coverage-istanbul/package.json
@@ -1,7 +1,7 @@
{
"name": "@vitest/coverage-istanbul",
"type": "module",
"version": "0.34.3",
"version": "0.34.4",
"description": "Istanbul coverage provider for Vitest",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
Expand Down
2 changes: 1 addition & 1 deletion packages/coverage-v8/package.json
@@ -1,7 +1,7 @@
{
"name": "@vitest/coverage-v8",
"type": "module",
"version": "0.34.3",
"version": "0.34.4",
"description": "V8 coverage provider for Vitest",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
Expand Down
2 changes: 1 addition & 1 deletion packages/expect/package.json
@@ -1,7 +1,7 @@
{
"name": "@vitest/expect",
"type": "module",
"version": "0.34.3",
"version": "0.34.4",
"description": "Jest's expect matchers as a Chai plugin",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
Expand Down
2 changes: 1 addition & 1 deletion packages/runner/package.json
@@ -1,7 +1,7 @@
{
"name": "@vitest/runner",
"type": "module",
"version": "0.34.3",
"version": "0.34.4",
"description": "Vitest test runner",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
Expand Down
2 changes: 1 addition & 1 deletion packages/snapshot/package.json
@@ -1,7 +1,7 @@
{
"name": "@vitest/snapshot",
"type": "module",
"version": "0.34.3",
"version": "0.34.4",
"description": "Vitest snapshot manager",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
Expand Down
2 changes: 1 addition & 1 deletion packages/spy/package.json
@@ -1,7 +1,7 @@
{
"name": "@vitest/spy",
"type": "module",
"version": "0.34.3",
"version": "0.34.4",
"description": "Lightweight Jest compatible spy implementation",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
Expand Down
2 changes: 1 addition & 1 deletion packages/ui/client/components/views/ViewReport.vue
Expand Up @@ -35,7 +35,7 @@ function escapeHtml(unsafe: string) {
function createHtmlError(filter: Convert, error: ErrorWithDiff) {
let htmlError = ''
if (error.message.includes('\x1B'))
if (error.message?.includes('\x1B'))
htmlError = `<b>${error.nameStr || error.name}</b>: ${filter.toHtml(escapeHtml(error.message))}`
const startStrWithX1B = error.stackStr?.includes('\x1B')
Expand Down
2 changes: 1 addition & 1 deletion packages/ui/package.json
@@ -1,7 +1,7 @@
{
"name": "@vitest/ui",
"type": "module",
"version": "0.34.3",
"version": "0.34.4",
"description": "UI for Vitest",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
Expand Down
2 changes: 1 addition & 1 deletion packages/utils/package.json
@@ -1,7 +1,7 @@
{
"name": "@vitest/utils",
"type": "module",
"version": "0.34.3",
"version": "0.34.4",
"description": "Shared Vitest utility functions",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
Expand Down
2 changes: 1 addition & 1 deletion packages/vite-node/package.json
@@ -1,6 +1,6 @@
{
"name": "vite-node",
"version": "0.34.3",
"version": "0.34.4",
"description": "Vite as Node.js runtime",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/package.json
@@ -1,7 +1,7 @@
{
"name": "vitest",
"type": "module",
"version": "0.34.3",
"version": "0.34.4",
"description": "A blazing fast unit test framework powered by Vite",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
Expand Down
7 changes: 3 additions & 4 deletions packages/vitest/src/api/setup.ts
Expand Up @@ -80,20 +80,19 @@ export function setup(vitestOrWorkspace: Vitest | WorkspaceProject, server?: Vit
return fs.readFile(id, 'utf-8')
},
async saveTestFile(id, content) {
// can save only already existing test file
if (!ctx.state.filesMap.has(id) || !existsSync(id))
return
throw new Error(`Test file "${id}" was not registered, so it cannot be updated using the API.`)
return fs.writeFile(id, content, 'utf-8')
},
async saveSnapshotFile(id, content) {
if (!ctx.snapshot.resolvedPaths.has(id))
return
throw new Error(`Snapshot file "${id}" does not exist.`)
await fs.mkdir(dirname(id), { recursive: true })
return fs.writeFile(id, content, 'utf-8')
},
async removeSnapshotFile(id) {
if (!ctx.snapshot.resolvedPaths.has(id) || !existsSync(id))
return
throw new Error(`Snapshot file "${id}" does not exist.`)
return fs.unlink(id)
},
snapshotSaved(snapshot) {
Expand Down
3 changes: 3 additions & 0 deletions packages/vitest/src/integrations/browser/server.ts
Expand Up @@ -36,6 +36,9 @@ export async function createBrowserServer(project: WorkspaceProject, configFile:
port: defaultBrowserPort,
}

// browser never runs in middleware mode
server.middlewareMode = false

config.server = server
config.server.fs ??= {}
config.server.fs.allow = config.server.fs.allow || []
Expand Down
5 changes: 4 additions & 1 deletion packages/vitest/src/node/config.ts
Expand Up @@ -49,9 +49,12 @@ export function resolveApiServerConfig<Options extends ApiConfig & UserConfig>(
}

if (api) {
if (!api.port)
if (!api.port && !api.middlewareMode)
api.port = defaultPort
}
else {
api = { middlewareMode: true }
}

return api
}
Expand Down
10 changes: 4 additions & 6 deletions packages/vitest/src/node/create.ts
@@ -1,11 +1,12 @@
import { resolve } from 'pathe'
import { createServer, mergeConfig } from 'vite'
import { mergeConfig } from 'vite'
import type { InlineConfig as ViteInlineConfig, UserConfig as ViteUserConfig } from 'vite'
import { findUp } from 'find-up'
import type { UserConfig, VitestRunMode } from '../types'
import { configFiles } from '../constants'
import { Vitest } from './core'
import { VitestPlugin } from './plugins'
import { createViteServer } from './vite'

export async function createVitest(mode: VitestRunMode, options: UserConfig, viteOverrides: ViteUserConfig = {}) {
const ctx = new Vitest(mode)
Expand All @@ -27,13 +28,10 @@ export async function createVitest(mode: VitestRunMode, options: UserConfig, vit
plugins: await VitestPlugin(options, ctx),
}

const server = await createServer(mergeConfig(config, mergeConfig(viteOverrides, { root: options.root })))
const server = await createViteServer(mergeConfig(config, mergeConfig(viteOverrides, { root: options.root })))

// optimizer needs .listen() to be called
if (ctx.config.api?.port || ctx.config.deps?.optimizer?.web?.enabled || ctx.config.deps?.optimizer?.ssr?.enabled)
if (ctx.config.api?.port)
await server.listen()
else
await server.pluginContainer.buildStart({})

return ctx
}
2 changes: 1 addition & 1 deletion packages/vitest/src/node/logger.ts
Expand Up @@ -139,7 +139,7 @@ export class Logger {

if (this.ctx.config.ui)
this.log(c.dim(c.green(` UI started at http://${this.ctx.config.api?.host || 'localhost'}:${c.bold(`${this.ctx.server.config.server.port}`)}${this.ctx.config.uiBase}`)))
else if (this.ctx.config.api)
else if (this.ctx.config.api?.port)
this.log(c.dim(c.green(` API started at http://${this.ctx.config.api?.host || 'localhost'}:${c.bold(`${this.ctx.config.api.port}`)}`)))

if (this.ctx.coverageProvider)
Expand Down
3 changes: 1 addition & 2 deletions packages/vitest/src/node/plugins/index.ts
Expand Up @@ -57,7 +57,7 @@ export async function VitestPlugin(options: UserConfig = {}, ctx = new Vitest('t

;(options as ResolvedConfig).defines = defines

let open: string | boolean | undefined
let open: string | boolean | undefined = false

if (testConfig.ui && testConfig.open)
open = testConfig.uiBase ?? '/__vitest__/'
Expand Down Expand Up @@ -140,7 +140,6 @@ export async function VitestPlugin(options: UserConfig = {}, ctx = new Vitest('t
// so we are making them truthy
process.env.PROD ??= PROD ? '1' : ''
process.env.DEV ??= DEV ? '1' : ''
process.env.SSR ??= '1'

for (const name in envs)
process.env[name] ??= envs[name]
Expand Down
1 change: 1 addition & 0 deletions packages/vitest/src/node/plugins/workspace.ts
Expand Up @@ -70,6 +70,7 @@ export function WorkspaceVitestPlugin(project: WorkspaceProject, options: Worksp
open: false,
hmr: false,
preTransformRequests: false,
middlewareMode: true,
fs: {
allow: resolveFsAllow(
project.ctx.config.root,
Expand Down
21 changes: 21 additions & 0 deletions packages/vitest/src/node/vite.ts
@@ -0,0 +1,21 @@
import type { InlineConfig } from 'vite'
import { createServer } from 'vite'

export async function createViteServer(inlineConfig: InlineConfig) {
// Vite prints an error (https://github.com/vitejs/vite/issues/14328)
// But Vitest works correctly either way
const error = console.error
console.error = (...args: any[]) => {
if (typeof args[0] === 'string' && args[0].includes('WebSocket server error:'))
return
error(...args)
}

const server = await createServer({
logLevel: 'error',
...inlineConfig,
})

console.error = error
return server
}
10 changes: 2 additions & 8 deletions packages/vitest/src/node/workspace.ts
Expand Up @@ -2,7 +2,6 @@ import { promises as fs } from 'node:fs'
import fg from 'fast-glob'
import mm from 'micromatch'
import { dirname, relative, resolve, toNamespacedPath } from 'pathe'
import { createServer } from 'vite'
import type { ViteDevServer, InlineConfig as ViteInlineConfig } from 'vite'
import { ViteNodeRunner } from 'vite-node/client'
import { ViteNodeServer } from 'vite-node/server'
Expand All @@ -14,6 +13,7 @@ import type { BrowserProvider } from '../types/browser'
import { getBrowserProvider } from '../integrations/browser'
import { isBrowserEnabled, resolveConfig } from './config'
import { WorkspaceVitestPlugin } from './plugins/workspace'
import { createViteServer } from './vite'

interface InitializeProjectOptions extends UserWorkspaceConfig {
workspaceConfigPath: string
Expand Down Expand Up @@ -44,13 +44,7 @@ export async function initializeProject(workspacePath: string | number, ctx: Vit
],
}

const server = await createServer(config)

// optimizer needs .listen() to be called
if (ctx.config.api?.port || project.config.deps?.optimizer?.web?.enabled || project.config.deps?.optimizer?.ssr?.enabled)
await server.listen()
else
await server.pluginContainer.buildStart({})
await createViteServer(config)

return project
}
Expand Down
4 changes: 4 additions & 0 deletions packages/vitest/src/runtime/setup.node.ts
Expand Up @@ -37,6 +37,10 @@ export async function setupGlobalEnv(config: ResolvedConfig, { environment }: Re
_require.extensions['.scss'] = () => ({})
_require.extensions['.sass'] = () => ({})
_require.extensions['.less'] = () => ({})
process.env.SSR = ''
}
else {
process.env.SSR = '1'
}

installSourcemapsSupport({
Expand Down
4 changes: 2 additions & 2 deletions packages/vitest/src/types/config.ts
@@ -1,4 +1,4 @@
import type { AliasOptions, CommonServerOptions, DepOptimizationConfig } from 'vite'
import type { AliasOptions, DepOptimizationConfig, ServerOptions } from 'vite'
import type { PrettyFormatOptions } from 'pretty-format'
import type { FakeTimerInstallOpts } from '@sinonjs/fake-timers'
import type { SequenceHooks, SequenceSetupFiles } from '@vitest/runner'
Expand All @@ -23,7 +23,7 @@ export type VitestEnvironment = BuiltinEnvironment | (string & Record<never, nev
export type VitestPool = 'browser' | 'threads' | 'child_process' | 'experimentalVmThreads'
export type CSSModuleScopeStrategy = 'stable' | 'scoped' | 'non-scoped'

export type ApiConfig = Pick<CommonServerOptions, 'port' | 'strictPort' | 'host'>
export type ApiConfig = Pick<ServerOptions, 'port' | 'strictPort' | 'host' | 'middlewareMode'>

export type { JSDOMOptions, HappyDOMOptions }

Expand Down
2 changes: 1 addition & 1 deletion packages/web-worker/package.json
@@ -1,7 +1,7 @@
{
"name": "@vitest/web-worker",
"type": "module",
"version": "0.34.3",
"version": "0.34.4",
"description": "Web Worker support for testing in Vitest",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
Expand Down
2 changes: 1 addition & 1 deletion packages/ws-client/package.json
@@ -1,7 +1,7 @@
{
"name": "@vitest/ws-client",
"type": "module",
"version": "0.34.3",
"version": "0.34.4",
"description": "WebSocket client wrapper for communicating with Vitest",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
Expand Down
1 change: 1 addition & 0 deletions test/core/package.json
Expand Up @@ -3,6 +3,7 @@
"private": true,
"scripts": {
"test": "vitest",
"dev": "vite",
"coverage": "vitest run --coverage"
},
"devDependencies": {
Expand Down
3 changes: 3 additions & 0 deletions test/core/vitest.config.ts → test/core/vite.config.ts
Expand Up @@ -41,6 +41,9 @@ export default defineConfig({
{ find: /^inline-lib$/, replacement: resolve(__dirname, 'projects', 'inline-lib') },
],
},
server: {
port: 3022,
},
test: {
name: 'core',
exclude: ['**/fixtures/**', '**/vm-wasm.test.ts', ...defaultExclude],
Expand Down

0 comments on commit 8250c56

Please sign in to comment.