Skip to content

Commit

Permalink
Merge branch 'main' into fix/omit-node-polyfills
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcel-G committed Sep 13, 2023
2 parents d7a3c66 + b75f91d commit d42f62d
Show file tree
Hide file tree
Showing 37 changed files with 2,834 additions and 578 deletions.
6 changes: 0 additions & 6 deletions docs/api/vi.md
Original file line number Diff line number Diff line change
Expand Up @@ -433,12 +433,6 @@ import.meta.env.MODE = 'test'
```
:::

:::warning
Vitest transforms all `import.meta.env` calls into `process.env`, so they can be easily changed at runtime. Node.js only supports string values as env parameters, while Vite supports several built-in envs as boolean (namely, `SSR`, `DEV`, `PROD`). To mimic Vite, set "truthy" values as env: `''` instead of `false`, and `'1'` instead of `true`.

But beware that you cannot rely on `import.meta.env.DEV === false` in this case. Use `!import.meta.env.DEV`. This also affects simple assigning, not just `vi.stubEnv` method.
:::

## vi.unstubAllEnvs

- **Type:** `() => Vitest`
Expand Down
22 changes: 22 additions & 0 deletions docs/config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1619,3 +1619,25 @@ By default Vitest will run all of your test cases even if some of them fail. Thi
- **Version:** Since Vitest 0.32.3

Retry the test specific number of times if it fails.

### onConsoleLog

- **Type**: `(log: string, type: 'stdout' | 'stderr') => false | void`

Custom handler for `console.log` in tests. If you return `false`, Vitest will not print the log to the console.

Can be useful for filtering out logs from third-party libraries.

```ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void {
if (log === 'message from third party library' && type === 'stdout')
return false
},
},
})
```

4 changes: 2 additions & 2 deletions docs/guide/index.md
Original file line number Diff line number Diff line change
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
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"name": "@vitest/monorepo",
"type": "module",
"version": "0.34.3",
"version": "0.34.4",
"private": true,
"packageManager": "pnpm@8.6.6",
"packageManager": "pnpm@8.7.4",
"description": "A blazing fast unit test framework powered by Vite",
"scripts": {
"ci": "ni && nr typecheck && nr lint && nr build && nr test:all",
Expand Down Expand Up @@ -75,7 +75,7 @@
},
"pnpm": {
"overrides": {
"vite": "^4.3.9",
"vite": "^4.4.9",
"vitest": "workspace:*"
},
"peerDependencyRules": {
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/package.json
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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
4 changes: 2 additions & 2 deletions packages/vite-node/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ await server.close()

Sometimes you might want to inspect the transformed code to investigate issues. You can set environment variable `VITE_NODE_DEBUG_DUMP=true` to let vite-node write the transformed result of each module under `.vite-node/dump`.

If you want to debug by modifying the dumped code, you can change the value of `VITE_NODE_DEBUG_DUMP` to `load` and search for the dumpped files and use them for executing.
If you want to debug by modifying the dumped code, you can change the value of `VITE_NODE_DEBUG_DUMP` to `load` and search for the dumped files and use them for executing.

```bash
VITE_NODE_DEBUG_DUMP=load vite-node example.ts
Expand All @@ -151,7 +151,7 @@ const server = new ViteNodeServer(viteServer, {

### Debug Execution

If the process get stuck, it might because there is a unresolvable circular dependencies, you can set `VITE_NODE_DEBUG_RUNNER=true` to vite-node warn about it.
If the process gets stuck, it might be because there are unresolvable circular dependencies. You can set `VITE_NODE_DEBUG_RUNNER=true` for vite-node to warn about this.

```bash
VITE_NODE_DEBUG_RUNNER=true vite-node example.ts
Expand Down
2 changes: 1 addition & 1 deletion packages/vite-node/package.json
Original file line number Diff line number Diff line change
@@ -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
30 changes: 16 additions & 14 deletions packages/vite-node/src/source-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,23 @@ export function withInlineSourcemap(result: TransformResult, options: {
if (!map || code.includes(VITE_NODE_SOURCEMAPPING_SOURCE))
return result

map.sources = map.sources?.map((source) => {
if (!source)
if ('sources' in map) {
map.sources = map.sources?.map((source) => {
if (!source)
return source
// sometimes files here are absolute,
// but they are considered absolute to the server url, not the file system
// this is a bug in Vite
// all files should be either absolute to the file system or relative to the source map file
if (isAbsolute(source)) {
const actualPath = (!source.startsWith(withTrailingSlash(options.root)) && source.startsWith('/'))
? resolve(options.root, source.slice(1))
: source
return relative(dirname(options.filepath), actualPath)
}
return source
// sometimes files here are absolute,
// but they are considered absolute to the server url, not the file system
// this is a bug in Vite
// all files should be either absolute to the file system or relative to the source map file
if (isAbsolute(source)) {
const actualPath = (!source.startsWith(withTrailingSlash(options.root)) && source.startsWith('/'))
? resolve(options.root, source.slice(1))
: source
return relative(dirname(options.filepath), actualPath)
}
return source
})
})
}

// to reduce the payload size, we only inline vite node source map, because it's also the only one we use
const OTHER_SOURCE_MAP_REGEXP = new RegExp(`//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`, 'gm')
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/package.json
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
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
16 changes: 6 additions & 10 deletions packages/vitest/src/integrations/browser/server.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,18 @@
import { createServer } from 'vite'
import { resolve } from 'pathe'
import { findUp } from 'find-up'
import { configFiles, defaultBrowserPort } from '../../constants'
import type { UserConfig } from '../../types/config'
import { defaultBrowserPort } from '../../constants'
import { ensurePackageInstalled } from '../../node/pkg'
import { resolveApiServerConfig } from '../../node/config'
import { CoverageTransform } from '../../node/plugins/coverageTransform'
import type { WorkspaceProject } from '../../node/workspace'
import { MocksPlugin } from '../../node/plugins/mocks'
import { resolveFsAllow } from '../../node/plugins/utils'

export async function createBrowserServer(project: WorkspaceProject, options: UserConfig) {
export async function createBrowserServer(project: WorkspaceProject, configFile: string | undefined) {
const root = project.config.root

await ensurePackageInstalled('@vitest/browser', root)

const configPath = options.config === false
? false
: options.config
? resolve(root, options.config)
: await findUp(configFiles, { cwd: root } as any)
const configPath = typeof configFile === 'string' ? configFile : false

const server = await createServer({
logLevel: 'error',
Expand All @@ -43,6 +36,9 @@ export async function createBrowserServer(project: WorkspaceProject, options: Us
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
1 change: 1 addition & 0 deletions packages/vitest/src/integrations/env/happy-dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export default <Environment>({
const { Window, GlobalWindow } = await importModule('happy-dom') as typeof import('happy-dom')
const win = new (GlobalWindow || Window)({
...happyDOM,
console: (console && global.console) ? global.console : undefined,
url: happyDOM.url || 'http://localhost:3000',
})

Expand Down
5 changes: 4 additions & 1 deletion packages/vitest/src/node/config.ts
Original file line number Diff line number Diff line change
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
21 changes: 8 additions & 13 deletions packages/vitest/src/node/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,20 +133,15 @@ export class Vitest {

await Promise.all(this._onSetServer.map(fn => fn()))

this.projects = await this.resolveWorkspace(options, cliOptions)
this.projects = await this.resolveWorkspace(cliOptions)

if (this.config.testNamePattern)
this.configOverride.testNamePattern = this.config.testNamePattern
}

private async createCoreWorkspace(options: UserConfig) {
const coreWorkspace = new WorkspaceProject(this.config.root, this)
await coreWorkspace.setServer(options, this.server, {
runner: this.runner,
server: this.vitenode,
})
this.coreWorkspaceProject = coreWorkspace
return coreWorkspace
private async createCoreProject() {
this.coreWorkspaceProject = await WorkspaceProject.createCoreProject(this)
return this.coreWorkspaceProject
}

public getCoreWorkspaceProject(): WorkspaceProject | null {
Expand All @@ -161,7 +156,7 @@ export class Vitest {
|| this.projects[0]
}

private async resolveWorkspace(options: UserConfig, cliOptions: UserConfig) {
private async resolveWorkspace(cliOptions: UserConfig) {
const configDir = this.server.config.configFile
? dirname(this.server.config.configFile)
: this.config.root
Expand All @@ -171,7 +166,7 @@ export class Vitest {
})

if (!workspaceConfigName)
return [await this.createCoreWorkspace(options)]
return [await this.createCoreProject()]

const workspaceConfigPath = join(configDir, workspaceConfigName)

Expand Down Expand Up @@ -259,7 +254,7 @@ export class Vitest {
if (
this.server.config.configFile === workspacePath
)
return this.createCoreWorkspace(options)
return this.createCoreProject()
return initializeProject(workspacePath, this, { workspaceConfigPath, test: cliOverrides })
})

Expand All @@ -268,7 +263,7 @@ export class Vitest {
})

if (!projects.length)
return [await this.createCoreWorkspace(options)]
return [await this.createCoreProject()]

const resolvedProjects = await Promise.all(projects)
const names = new Set<string>()
Expand Down
Loading

0 comments on commit d42f62d

Please sign in to comment.