Skip to content
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
9 changes: 6 additions & 3 deletions docs/config/update.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ outline: deep

# update <CRoot /> {#update}

- **Type:** `boolean`
- **Type:** `boolean | 'new' | 'all'`
- **Default:** `false`
- **CLI:** `-u`, `--update`, `--update=false`
- **CLI:** `-u`, `--update`, `--update=false`, `--update=new`

Update snapshot files. This will update all changed snapshots and delete obsolete ones.
Update snapshot files. The behaviour depends on the value:

- `true` or `'all'`: updates all changed snapshots and delete obsolete ones
- `new`: generates new snapshots without changing or deleting obsolete ones
4 changes: 2 additions & 2 deletions docs/guide/cli-generated.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ Path to config file

### update

- **CLI:** `-u, --update`
- **CLI:** `-u, --update [type]`
- **Config:** [update](/config/update)

Update snapshot
Update snapshot (accepts boolean, "new" or "all")

### watch

Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const RPC_ID: string
const METHOD = getBrowserState().method
export const ENTRY_URL: string = `${
location.protocol === 'https:' ? 'wss:' : 'ws:'
}//${HOST}/__vitest_browser_api__?type=${PAGE_TYPE}&rpcId=${RPC_ID}&sessionId=${getBrowserState().sessionId}&projectName=${getBrowserState().config.name || ''}&method=${METHOD}&token=${(window as any).VITEST_API_TOKEN || '0'}`
}//${HOST}/__vitest_browser_api__?type=${PAGE_TYPE}&rpcId=${RPC_ID}&sessionId=${getBrowserState().sessionId}&projectName=${encodeURIComponent(getBrowserState().config.name || '')}&method=${METHOD}&token=${(window as any).VITEST_API_TOKEN || '0'}`

const onCancelCallbacks: ((reason: CancelReason) => void)[] = []

Expand Down
8 changes: 5 additions & 3 deletions packages/mocker/src/node/hoistMocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,8 @@ export function hoistMocks(
} = options

// hoist at the start of the file, after the hashbang
let hoistIndex = hashbangRE.exec(code)?.[0].length ?? 0
const hashbangEnd = hashbangRE.exec(code)?.[0].length ?? 0
let hoistIndex = hashbangEnd

let hoistedModuleImported = false

Expand Down Expand Up @@ -535,11 +536,12 @@ export function hoistMocks(
const utilityImports = [...usedUtilityExports]
// "vi" or "vitest" is imported from a module other than "vitest"
if (utilityImports.some(name => idToImportMap.has(name))) {
s.prepend(API_NOT_FOUND_CHECK(utilityImports))
s.appendLeft(hashbangEnd, API_NOT_FOUND_CHECK(utilityImports))
}
// if "vi" or "vitest" are not imported at all, import them
else if (utilityImports.length) {
s.prepend(
s.appendLeft(
hashbangEnd,
`import { ${[...usedUtilityExports].join(', ')} } from ${JSON.stringify(
hoistedModule,
)}\n`,
Expand Down
3 changes: 2 additions & 1 deletion packages/vitest/src/node/cli/cli-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ export const cliOptionsConfig: VitestCLIOptions = {
},
update: {
shorthand: 'u',
description: 'Update snapshot',
description: 'Update snapshot (accepts boolean, "new" or "all")',
argument: '[type]',
},
watch: {
shorthand: 'w',
Expand Down
4 changes: 3 additions & 1 deletion packages/vitest/src/node/config/resolveConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -508,7 +508,9 @@ export function resolveConfig(
expand: resolved.expandSnapshotDiff ?? false,
snapshotFormat: resolved.snapshotFormat || {},
updateSnapshot:
isCI && !UPDATE_SNAPSHOT ? 'none' : UPDATE_SNAPSHOT ? 'all' : 'new',
UPDATE_SNAPSHOT === 'all' || UPDATE_SNAPSHOT === 'new'
? UPDATE_SNAPSHOT
: isCI && !UPDATE_SNAPSHOT ? 'none' : UPDATE_SNAPSHOT ? 'all' : 'new',
resolveSnapshotPath: options.resolveSnapshotPath,
// resolved inside the worker
snapshotEnvironment: null as any,
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/node/types/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ export interface InlineConfig {
*
* @default false
*/
update?: boolean
update?: boolean | 'all' | 'new'

/**
* Watch mode
Expand Down
5 changes: 5 additions & 0 deletions test/browser/fixtures/project-name-encoding/basic.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { expect, test } from 'vitest'

test('basic test', () => {
expect(true).toBe(true)
})
11 changes: 11 additions & 0 deletions test/browser/fixtures/project-name-encoding/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { defineConfig } from 'vitest/config'

export default defineConfig({
test: {
name: 'Components & Hooks',
browser: {
enabled: true,
headless: true,
},
},
})
2 changes: 1 addition & 1 deletion test/browser/fixtures/user-event/wheel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ describe.for([

await (testType === 'userEvent' ? userEvent.wheel(selector, options) : selector.wheel(options))

expect(wheel).toHaveBeenCalledOnce()
await expect.poll(() => wheel).toHaveBeenCalledOnce()
expect(wheel.mock.calls[0][0].deltaX).toBe(deltaX)
expect(wheel.mock.calls[0][0].deltaY).toBe(deltaY)
})
Expand Down
21 changes: 21 additions & 0 deletions test/browser/specs/project-name-encoding.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { expect, test } from 'vitest'
import { instances, provider, runBrowserTests } from './utils'

test('runs tests correctly when project name contains special characters', async () => {
const { stderr, stdout, exitCode, ctx } = await runBrowserTests({
root: './fixtures/project-name-encoding',
browser: {
provider,
instances,
},
})

expect(stderr).toBe('')
expect(exitCode).toBe(0)

const projectName = ctx.config.name

instances.forEach(({ browser }) => {
expect(stdout).toReportPassedTest('basic.test.ts', `${projectName} (${browser})`)
})
})
74 changes: 33 additions & 41 deletions test/browser/specs/to-match-screenshot.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import type { ViteUserConfig } from 'vitest/config'
import type { TestFsStructure } from '../../test-utils'
import { platform } from 'node:os'
import { resolve } from 'node:path'
import { describe, expect, test } from 'vitest'
import { runVitestCli, useFS } from '../../test-utils'
import { runInlineTests } from '../../test-utils'
import { extractToMatchScreenshotPaths } from '../fixtures/expect-dom/utils'
import utilsContent from '../fixtures/expect-dom/utils?raw'
import { provider } from '../settings'

const testFilename = 'basic.test.ts'
const testName = 'screenshot-snapshot'
Expand All @@ -27,57 +27,46 @@ test('${testName}', async ({ expect }) => {

const browser = 'chromium'

async function runInlineTests(
async function runBrowserTests(
structure: TestFsStructure,
config: ViteUserConfig['test'] = {},
) {
const root = resolve(process.cwd(), `vitest-test-${crypto.randomUUID()}`)

const fs = useFS(root, {
return runInlineTests({
...structure,
'vitest.config.ts': `
import { playwright } from '@vitest/browser-playwright'
export default {
test: {
browser: {
enabled: true,
screenshotFailures: false,
provider: playwright(),
headless: true,
instances: [{ browser: ${JSON.stringify(browser)} }],
'vitest.config.js': `
import { playwright } from '@vitest/browser-playwright'
export default {
test: {
browser: {
enabled: true,
screenshotFailures: false,
provider: playwright(),
headless: true,
instances: [{ browser: ${JSON.stringify(browser)} }],
},
reporters: ['verbose'],
...${JSON.stringify(config)},
},
reporters: ['verbose'],
...${JSON.stringify(config)},
},
}`,
})

const vitest = await runVitestCli({
nodeOptions: {
env: {
CI: 'false',
GITHUB_ACTIONS: undefined,
NO_COLOR: 'true',
},
}`,
}, {
$cliOptions: {
watch: true,
},
}, '--root', root, '--watch')

return {
fs,
root,
...vitest,
}
})
}

describe('--watch', () => {
describe.runIf(provider.name === 'playwright')('--watch', () => {
test(
'fails when creating a snapshot for the first time and does NOT update it afterwards',
async () => {
const { fs, stderr, vitest } = await runInlineTests(
const { fs, stderr, vitest } = await runBrowserTests(
{
[testFilename]: testContent,
'utils.ts': utilsContent,
},
{
update: 'new',
},
)

const [referencePath] = extractToMatchScreenshotPaths(stderr, testName)
Expand All @@ -102,11 +91,14 @@ describe('--watch', () => {
test(
'creates a reference and fails when changing the DOM content',
async () => {
const { fs, stderr, vitest } = await runInlineTests(
const { fs, stderr, vitest } = await runBrowserTests(
{
[testFilename]: testContent,
'utils.ts': utilsContent,
},
{
update: 'new',
},
)

expect(stderr).toContain(`No existing reference screenshot found; a new one was created. Review it before running tests again.\n\nReference screenshot:`)
Expand All @@ -126,7 +118,7 @@ describe('--watch', () => {
test(
'creates snapshot and does NOT update it if reference matches',
async () => {
const { fs, stderr, vitest } = await runInlineTests(
const { fs, stderr, vitest } = await runBrowserTests(
{
[testFilename]: testContent,
'utils.ts': utilsContent,
Expand Down Expand Up @@ -174,7 +166,7 @@ describe('--watch', () => {
test(
'creates snapshot and updates it if reference mismatches',
async () => {
const { fs, stderr, vitest } = await runInlineTests(
const { fs, stderr, vitest } = await runBrowserTests(
{
[testFilename]: testContent,
'utils.ts': utilsContent,
Expand Down
41 changes: 18 additions & 23 deletions test/cli/test/config-loader.test.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,28 @@
import { expect, test } from 'vitest'
import { runVitestCli } from '../../test-utils'
import { runVitest } from '../../test-utils'

const isTypeStrippingSupported = !!process.features.typescript

test('configLoader default', async () => {
const { vitest, exitCode } = await runVitestCli(
'run',
'--root',
'fixtures/config-loader',
)
if (!isTypeStrippingSupported) {
expect(vitest.stderr).toContain('failed to load config')
expect(exitCode).not.toBe(0)
}
else {
expect(exitCode).toBe(0)
}
test.runIf(isTypeStrippingSupported)('configLoader native', async () => {
const { stderr, exitCode } = await runVitest({
root: 'fixtures/config-loader',
$cliOptions: {
configLoader: 'native',
},
})
expect(stderr).toBe('')
expect(exitCode).toBe(0)
})

test('configLoader runner', async () => {
const { vitest, exitCode } = await runVitestCli(
'run',
'--root',
'fixtures/config-loader',
'--configLoader',
'runner',
)
const { vitest, exitCode } = await runVitest({
root: 'fixtures/config-loader',
$cliOptions: {
configLoader: 'runner',
},
})
expect(vitest.stderr).toBe('')
expect(vitest.stdout).toContain('✓ node')
expect(vitest.stdout).toContain('✓ browser (chromium)')
expect(vitest.stdout).toContain('✓ |node|')
expect(vitest.stdout).toContain('✓ |browser (chromium)|')
expect(exitCode).toBe(0)
})
4 changes: 2 additions & 2 deletions test/cli/test/projects.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ it('correctly inherits the root config', async () => {
it('fails if workspace is empty', async () => {
const { stderr } = await runVitest({
projects: [],
})
}, [], { fails: true })
expect(stderr).toContain('No projects were found. Make sure your configuration is correct. The projects definition: [].')
})

Expand All @@ -133,7 +133,7 @@ it('fails if workspace is filtered by the project', async () => {
projects: [
'./vitest.config.js',
],
})
}, [], { fails: true })
expect(stderr).toContain(`No projects were found. Make sure your configuration is correct. The filter matched no projects: non-existing. The projects definition: [
"./vitest.config.js"
].`)
Expand Down
4 changes: 2 additions & 2 deletions test/cli/test/unhandled-rejections.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ describe('dangerouslyIgnoreUnhandledErrors', () => {

new Promise((_, reject) => reject(new Error("intentional unhandled error")))
`,
}, config)
}, config, { fails: true })
}
})

Expand All @@ -59,7 +59,7 @@ test('unhandled rejections of main thread are reported even when no reporter is
config: false,
globalSetup: ['setup-unhandled-rejections.js'],
reporters: [{ onInit: () => {} }],
})
}, { fails: true })

expect(exitCode).toBe(1)
expect(stderr).toContain('Unhandled Rejection')
Expand Down
Loading
Loading