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
29 changes: 29 additions & 0 deletions docs/config/coverage.md
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,35 @@ Sets thresholds to 100 for files matching the glob pattern.
Set to array of class method names to ignore for coverage.
See [istanbul documentation](https://github.com/istanbuljs/nyc#ignoring-methods) for more information.

## coverage.ignoreNode <Version>5.1.0</Version> {#coverage-ignorenode}

- **Type:** `(node: Node, type: 'function' | 'statement' | 'branch') => boolean | 'ignore-this-and-nested-nodes' | void`
- **Available for providers:** `'v8'`

Filter to ignore code from coverage based on its AST node. Vitest calls it for each node of the transformed code, together with the kind of coverage the node counts for. Return `true` to ignore the node, or `'ignore-this-and-nested-nodes'` to also ignore all nodes inside it.

This is useful for code that doesn't exist in the source file and can't carry an [ignore hint](/guide/coverage#ignoring-code), like code that compilers or other plugins generate. Since the nodes come from the code after Vite's transforms, the filter sees exactly what the plugins generated.

Vitest's built-in filters run first, so nodes that Vitest already ignores, like its own transform artifacts, are never passed to this function.

```ts
import { defineConfig } from 'vitest/config'

export default defineConfig({
test: {
coverage: {
provider: 'v8',
ignoreNode: (node, type) =>
type === 'statement'
&& node.type === 'ExpressionStatement'
&& node.expression.type === 'CallExpression'
&& node.expression.callee.type === 'Identifier'
&& node.expression.callee.name === '__generatedHelper',
},
},
})
```

## coverage.watermarks

- **Type:**
Expand Down
4 changes: 3 additions & 1 deletion packages/coverage-v8/src/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ export class V8CoverageProvider extends BaseCoverageProvider implements Coverage
return {}
}

return (await astV8ToIstanbul({
return (await astV8ToIstanbul<Vite.ESTree.Node>({
code: result.code,
sourceMap: result.map,
ast,
Expand Down Expand Up @@ -372,6 +372,8 @@ export class V8CoverageProvider extends BaseCoverageProvider implements Coverage
) {
return 'ignore-this-and-nested-nodes'
}

return this.options.ignoreNode?.(node, type)
},
})) as libCoverage.CoverageMapData
}
Expand Down
18 changes: 17 additions & 1 deletion packages/vitest/src/node/types/coverage.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { ReportOptions } from '@vitest/istanbul-lib-report'
import type { Arrayable } from '@vitest/utils'
import type { TransformResult as ViteTransformResult } from 'vite'
import type { ESTree, TransformResult as ViteTransformResult } from 'vite'
import type { AfterSuiteRunMeta } from '../../types/general'
import type {
RuntimeCoverageModuleLoader,
Expand Down Expand Up @@ -269,6 +269,22 @@ export interface CoverageOptions {
*/
ignoreClassMethods?: string[]

/**
* Filter to ignore code from coverage based on its AST node.
* Called only for nodes that Vitest's built-in filters don't already ignore.
* Return `'ignore-this-and-nested-nodes'` to also ignore all nodes inside the given node.
* Supported only by `v8` provider.
*
* @example
* ```ts
* ignoreNode: (node, type) => type === 'statement' && node.type === 'DebuggerStatement'
* ```
*/
ignoreNode?: (
node: ESTree.Node,
type: 'function' | 'statement' | 'branch',
) => boolean | 'ignore-this-and-nested-nodes' | void

/**
* Custom instrumenter factory to use instead of the default `@vitest/istanbul-lib-instrument`.
*
Expand Down
14 changes: 14 additions & 0 deletions test/coverage-test/fixtures/src/ignore-node.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { sum } from './math'

export function calculate(a: number, b: number) {
__generatedHelper()

if (a > b) {
const total = sum(a, b)
return total
}

return sum(b, a)
}

function __generatedHelper() {}
6 changes: 6 additions & 0 deletions test/coverage-test/fixtures/test/ignore-node-fixture.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { expect, test } from 'vitest'
import { calculate } from '../src/ignore-node'

test('cover some lines', () => {
expect(calculate(2, 1)).toBe(3)
})
37 changes: 37 additions & 0 deletions test/coverage-test/test/configuration-options.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,3 +328,40 @@ test('custom instrumenter', () => {
instrumenter: factory,
})
})

test('ignoreNode', () => {
assertType<Coverage>({
provider: 'v8',
ignoreNode: (node, type) => type === 'branch' && node.type === 'IfStatement',
})

assertType<Coverage>({
provider: 'v8',
ignoreNode: () => 'ignore-this-and-nested-nodes',
})

assertType<Coverage>({
provider: 'v8',
ignoreNode: () => {},
})

assertType<Coverage>({
provider: 'v8',
// @ts-expect-error -- must return a boolean, 'ignore-this-and-nested-nodes' or nothing
ignoreNode: () => 'ignore-everything',
})

assertType<Coverage>({
provider: 'v8',
ignoreNode: (node) => {
if (node.type === 'IfStatement' && node.alternate) {
return true
}

// @ts-expect-error -- CatchClause has no alternate. Should fail if node types work correctly
if (node.type === 'CatchClause' && node.alternate) {
return true
}
},
})
})
60 changes: 60 additions & 0 deletions test/coverage-test/test/ignore-node.v8.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { expect } from 'vitest'
import { isNativeRunner, readCoverageMap, runVitest, test } from '../utils'

/* See {@link file://./../fixtures/src/ignore-node.ts} */
const filename = '<process-cwd>/fixtures/src/ignore-node.ts'

test('{ ignoreNode } excludes the matching nodes', async () => {
await runVitest({
include: ['fixtures/test/ignore-node-fixture.test.ts'],
coverage: {
reporter: 'json',
ignoreNode: (node, type) => {
if (
type === 'statement' &&
node.type === 'ExpressionStatement' &&
node.expression.type === 'CallExpression' &&
node.expression.callee.type === 'Identifier' &&
node.expression.callee.name === '__generatedHelper'
) {
return true
}

return type === 'branch' && node.type === 'IfStatement'
},
},
})

const coverageMap = await readCoverageMap()
const fileCoverage = coverageMap.fileCoverageFor(filename)
const lines = fileCoverage.getLineCoverage()

expect(lines[4]).toBeUndefined()

expect(fileCoverage.getBranchCoverageByLine()[6]).toBeUndefined()

expect(lines[7]).toBeGreaterThanOrEqual(1)
expect(lines[8]).toBeGreaterThanOrEqual(1)

expect(lines[11]).toBe(0)
})

test('{ ignoreNode } is not called for nodes that Vitest already ignores', async ({ skip }) => {
skip(isNativeRunner(), 'Native runner does not transform imports to __vite_ssr_import_')

const declarators: string[] = []

await runVitest({
include: ['fixtures/test/ignore-node-fixture.test.ts'],
coverage: {
reporter: 'json',
ignoreNode: (node) => {
if (node.type === 'VariableDeclarator' && node.id.type === 'Identifier') {
declarators.push(node.id.name)
}
},
},
})

expect(declarators).toEqual(['total'])
})