Skip to content

Commit

Permalink
Merge branch 'main' into docs/onConsoleLog
Browse files Browse the repository at this point in the history
  • Loading branch information
fenghan34 committed Mar 16, 2024
2 parents b640910 + a8da192 commit c5807d2
Show file tree
Hide file tree
Showing 36 changed files with 358 additions and 63 deletions.
12 changes: 2 additions & 10 deletions docs/config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1736,18 +1736,10 @@ Test above this limit will be queued to run when available slot appears.

### cache<NonProjectOption />

- **Type**: `false | { dir? }`
- **Type**: `false`
- **CLI**: `--no-cache`, `--cache=false`

Options to configure Vitest cache policy. At the moment Vitest stores cache for test results to run the longer and failed tests first.

#### cache.dir

- **Type**: `string`
- **Default**: `node_modules/.vitest`
- **CLI**: `--cache.dir=./cache`

Path to cache directory.
Use this option if you want to disable the cache feature. At the moment Vitest stores cache for test results to run the longer and failed tests first.

### sequence

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@vitest/monorepo",
"type": "module",
"version": "1.3.1",
"version": "1.4.0",
"private": true,
"packageManager": "pnpm@8.10.3",
"description": "Next generation testing framework powered by Vite",
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": "1.3.1",
"version": "1.4.0",
"description": "Browser running for Vitest",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/client/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ async function updateFilesLocations(files: File[]) {
if (task.location) {
const { line, column } = originalPositionFor(traceMap, task.location)
if (line != null && column != null)
task.location = { line, column: column + 1 }
task.location = { line, column: task.each ? column : column + 1 }
}
if ('tasks' in task)
task.tasks.forEach(updateLocation)
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": "1.3.1",
"version": "1.4.0",
"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": "1.3.1",
"version": "1.4.0",
"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": "1.3.1",
"version": "1.4.0",
"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": "1.3.1",
"version": "1.4.0",
"description": "Vitest test runner",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
Expand Down
16 changes: 12 additions & 4 deletions packages/runner/src/suite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ function createSuiteCollector(name: string, factory: SuiteFactory = () => { }, m
Error.stackTraceLimit = 10
const error = new Error('stacktrace').stack!
Error.stackTraceLimit = limit
const stack = findStackTrace(error)
const stack = findStackTrace(error, task.each ?? false)
if (stack)
task.location = stack
}
Expand Down Expand Up @@ -226,7 +226,9 @@ function createSuiteCollector(name: string, factory: SuiteFactory = () => { }, m
if (stack) {
suite.location = {
line: stack.line,
column: stack.column,
// because source map is boundary based, this line leads to ")" in test.each()[(]),
// but it should be the next opening bracket - here we assume it's on the same line
column: each ? stack.column + 1 : stack.column,
}
}
}
Expand Down Expand Up @@ -430,7 +432,7 @@ function formatTemplateString(cases: any[], args: any[]): any[] {
return res
}

function findStackTrace(error: string) {
function findStackTrace(error: string, each: boolean) {
// first line is the error message
// and the first 3 stacks are always from the collector
const lines = error.split('\n').slice(4)
Expand All @@ -439,7 +441,13 @@ function findStackTrace(error: string) {
if (stack && stack.file === getTestFilepath()) {
return {
line: stack.line,
column: stack.column,
/**
* test.each([1, 2])('name')
* ^ leads here, but should
* ^ lead here
* in source maps it's the same boundary, so it just points to the start of it
*/
column: each ? stack.column + 1 : stack.column,
}
}
}
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": "1.3.1",
"version": "1.4.0",
"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": "1.3.1",
"version": "1.4.0",
"description": "Lightweight Jest compatible spy implementation",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
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": "1.3.1",
"version": "1.4.0",
"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": "1.3.1",
"version": "1.4.0",
"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
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "vite-node",
"type": "module",
"version": "1.3.1",
"version": "1.4.0",
"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
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "vitest",
"type": "module",
"version": "1.3.1",
"version": "1.4.0",
"description": "Next generation testing framework powered by Vite",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
Expand Down
4 changes: 2 additions & 2 deletions packages/vitest/src/node/cache/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ export class VitestCache {
return this.stats.getStats(key)
}

static resolveCacheDir(root: string, dir: string | undefined, projectName: string | undefined) {
const baseDir = slash(dir || 'node_modules/.vitest')
static resolveCacheDir(root: string, dir?: string, projectName?: string) {
const baseDir = slash(dir || 'node_modules/.vite/vitest')
return projectName
? resolve(root, baseDir, crypto.createHash('md5').update(projectName, 'utf-8').digest('hex'))
: resolve(root, baseDir)
Expand Down
9 changes: 4 additions & 5 deletions packages/vitest/src/node/cli/cli-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -549,14 +549,13 @@ export const cliOptionsConfig: VitestCLIOptions = {
description: 'Enable cache',
argument: '', // allow only boolean
subcommands: {
dir: {
description: 'Path to the cache directory',
argument: '<path>',
normalize: true,
},
dir: null,
},
default: true,
// cache can only be "false" or an object
transform(cache) {
if (typeof cache !== 'boolean' && cache)
throw new Error('--cache.dir is deprecated')
if (cache)
return {}
return cache
Expand Down
18 changes: 15 additions & 3 deletions packages/vitest/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -446,9 +446,21 @@ export function resolveConfig(
resolved.css.modules.classNameStrategy ??= 'stable'
}

resolved.cache ??= { dir: '' }
if (resolved.cache)
resolved.cache.dir = VitestCache.resolveCacheDir(resolved.root, resolved.cache.dir, resolved.name)
if (resolved.cache !== false) {
let cacheDir = VitestCache.resolveCacheDir('', resolve(viteConfig.cacheDir, 'vitest'), resolved.name)

if (resolved.cache && resolved.cache.dir) {
console.warn(
c.yellow(
`${c.inverse(c.yellow(' Vitest '))} "cache.dir" is deprecated, use Vite's "cacheDir" instead if you want to change the cache director. Note caches will be written to "cacheDir\/vitest"`,
),
)

cacheDir = VitestCache.resolveCacheDir(resolved.root, resolved.cache.dir, resolved.name)
}

resolved.cache = { dir: cacheDir }
}

resolved.sequence ??= {} as any
if (resolved.sequence.shuffle && typeof resolved.sequence.shuffle === 'object') {
Expand Down
20 changes: 18 additions & 2 deletions packages/vitest/src/node/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import type { defineWorkspace } from 'vitest/config'
import type { ArgumentsType, CoverageProvider, OnServerRestartHandler, Reporter, ResolvedConfig, UserConfig, UserWorkspaceConfig, VitestRunMode } from '../types'
import { hasFailed, noop, slash, toArray, wildcardPatternToRegExp } from '../utils'
import { getCoverageProvider } from '../integrations/coverage'
import type { BrowserProvider } from '../types/browser'
import { CONFIG_NAMES, configFiles, workspacesFiles as workspaceFiles } from '../constants'
import { rootDir } from '../paths'
import { WebSocketReporter } from '../api/setup'
Expand Down Expand Up @@ -43,14 +42,14 @@ export class Vitest {
cache: VitestCache = undefined!
reporters: Reporter[] = undefined!
coverageProvider: CoverageProvider | null | undefined
browserProvider: BrowserProvider | undefined
logger: Logger
pool: ProcessPool | undefined

vitenode: ViteNodeServer = undefined!

invalidates: Set<string> = new Set()
changedTests: Set<string> = new Set()
watchedTests: Set<string> = new Set()
filenamePattern?: string
runningPromise?: Promise<void>
closingPromise?: Promise<void>
Expand Down Expand Up @@ -623,6 +622,14 @@ export class Vitest {
return

this._rerunTimer = setTimeout(async () => {
// run only watched tests
if (this.watchedTests.size) {
this.changedTests.forEach((test) => {
if (!this.watchedTests.has(test))
this.changedTests.delete(test)
})
}

if (this.changedTests.size === 0) {
this.invalidates.clear()
return
Expand Down Expand Up @@ -665,6 +672,15 @@ export class Vitest {
})
}

/**
* Watch only the specified tests. If no tests are provided, all tests will be watched.
*/
public watchTests(tests: string[]) {
this.watchedTests = new Set(
tests.map(test => slash(test)),
)
}

private unregisterWatcher = noop
private registerWatcher() {
const updateLastChanged = (filepath: string) => {
Expand Down
4 changes: 2 additions & 2 deletions packages/vitest/src/runtime/console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export function createCustomConsole(state: WorkerGlobalState) {

const stdout = new Writable({
write(data, encoding, callback) {
const id = state?.current?.id ?? getTaskIdByStack(state.ctx.config.root)
const id = state?.current?.id || state?.current?.file?.id || getTaskIdByStack(state.ctx.config.root)
let timer = timers.get(id)
if (timer) {
timer.stdoutTime = timer.stdoutTime || RealDate.now()
Expand All @@ -106,7 +106,7 @@ export function createCustomConsole(state: WorkerGlobalState) {
})
const stderr = new Writable({
write(data, encoding, callback) {
const id = state?.current?.id ?? getTaskIdByStack(state.ctx.config.root)
const id = state?.current?.id || state?.current?.file?.id || getTaskIdByStack(state.ctx.config.root)
let timer = timers.get(id)
if (timer) {
timer.stderrTime = timer.stderrTime || RealDate.now()
Expand Down
10 changes: 9 additions & 1 deletion packages/vitest/src/runtime/runners/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ export class VitestTestRunner implements VitestRunner {
this.snapshotClient.clear()
}

onAfterRunFiles() {
this.workerState.current = undefined
}

async onAfterRunSuite(suite: Suite) {
if (this.config.logHeapUsage && typeof process !== 'undefined')
suite.result!.heap = process.memoryUsage().heapUsed
Expand All @@ -44,6 +48,8 @@ export class VitestTestRunner implements VitestRunner {
if (result)
await rpc().snapshotSaved(result)
}

this.workerState.current = suite.suite
}

onAfterRunTask(test: Task) {
Expand All @@ -52,7 +58,7 @@ export class VitestTestRunner implements VitestRunner {
if (this.config.logHeapUsage && typeof process !== 'undefined')
test.result!.heap = process.memoryUsage().heapUsed

this.workerState.current = undefined
this.workerState.current = test.suite
}

onCancel(_reason: CancelReason) {
Expand Down Expand Up @@ -81,6 +87,8 @@ export class VitestTestRunner implements VitestRunner {
// (e.g. `toMatchSnapshot`) specifies "filepath" / "name" pair explicitly
await this.snapshotClient.startCurrentRun(suite.filepath, '__default_name_', this.workerState.config.snapshotOptions)
}

this.workerState.current = suite
}

onBeforeTryTask(test: Task) {
Expand Down
10 changes: 8 additions & 2 deletions packages/vitest/src/types/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -624,10 +624,13 @@ export interface InlineConfig {

/**
* Options for configuring cache policy.
* @default { dir: 'node_modules/.vitest' }
* @default { dir: 'node_modules/.vite/vitest' }
*/
cache?: false | {
dir?: string
/**
* @deprecated Use Vite's "cacheDir" instead if you want to change the cache director. Note caches will be written to "cacheDir\/vitest".
*/
dir: string
}

/**
Expand Down Expand Up @@ -854,6 +857,9 @@ export interface ResolvedConfig extends Omit<Required<UserConfig>, 'config' | 'f
}

cache: {
/**
* @deprecated
*/
dir: string
} | false

Expand Down
2 changes: 1 addition & 1 deletion packages/web-worker/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@vitest/web-worker",
"type": "module",
"version": "1.3.1",
"version": "1.4.0",
"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
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@vitest/ws-client",
"type": "module",
"version": "1.3.1",
"version": "1.4.0",
"description": "WebSocket client wrapper for communicating with Vitest",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
Expand Down
5 changes: 5 additions & 0 deletions test/config/fixtures/cache/basic.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { expect, test } from "vitest";

test('', () => {
expect(true).toBe(true)
})
Loading

0 comments on commit c5807d2

Please sign in to comment.