Skip to content

Conversation

@DevJoaoLopes
Copy link
Contributor

@DevJoaoLopes DevJoaoLopes commented Jan 9, 2026

Description

Fixes coverage.include/coverage.exclude glob matching so it behaves like test.include/test.exclude (relative to the project root), addressing Vitest v4 regressions reported in #9395.

In v4, matching was done against the full (absolute) filename with picomatch using contains: true and ignore, which made patterns such as ./*.ts or **/foo/** unexpectedly match parts of the absolute path (including the CWD), causing everything to be excluded.

This change:

  • Matches include/exclude against the path relative to each project root when the file is inside the project, so top-level-only excludes like ./*.ts work as expected.
  • Avoids excluding the whole project when the CWD contains an excluded segment (e.g. /.../foo/...), by using relative paths for in-project files and only using the absolute filename for truly external files.
  • Keeps allowExternal: false semantics by skipping external files instead of incorrectly failing matches for everything.
  • Adjusts the glob cache key to include the root (so multi-project roots don’t share incorrect cached results).

fix #9395

Please don't delete this checklist! Before submitting the PR, please make sure you do the following:

  • It's really useful if your PR references an issue where it is discussed ahead of time. If the feature is substantial or introduces breaking changes without a discussion, PR might be closed.
  • Ideally, include a test that fails without this PR but passes with it.
  • Please, don't make changes to pnpm-lock.yaml unless you introduce a new test example.
  • Please check Allow edits by maintainers to make review process faster. Note that this option is not available for repositories that are owned by Github organizations.

Tests

  • Run the tests with pnpm test:ci.

Documentation

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs command.

Changesets

  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.

@netlify
Copy link

netlify bot commented Jan 9, 2026

Deploy Preview for vitest-dev ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit c23a1ad
🔍 Latest deploy log https://app.netlify.com/projects/vitest-dev/deploys/697674d760b1a80008b0af2e
😎 Deploy Preview https://deploy-preview-9426--vitest-dev.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

Copy link
Member

@AriPerkkio AriPerkkio left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you check the failing tests and add new tests to test/coverage-test to validate this fix? Or maybe use the test/coverage-test/test/include-exclude.test.ts.

@DevJoaoLopes
Copy link
Contributor Author

Could you check the failing tests and add new tests to test/coverage-test to validate this fix? Or maybe use the test/coverage-test/test/include-exclude.test.ts.

@AriPerkkio Sure, I apologize for not doing it from the beginning... I'll work on it. 😅

return false
}
for (const projectRoot of roots) {
const relativePath = slash(relative(projectRoot, filename))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't this actually change how defined globs are interpreted when using --project filter?

  • When it's not used, globs are relative to root
  • When it's used, globs are relative to project's root
├── package.json
├── vitest.config.ts
└── packages
    ├── one
    │   ├── src
    │   │   └── math.ts
    │   └── test
    │       └── math.test.ts
    └── two
        ├── src
        │   └── get-user.ts
        └── test
            └── get-user.test.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    coverage: {
      include: ["./packages/**/*.ts"],
    },

    projects: [
      {
        test: {
          name: "One",
          root: "./packages/one",
        },
      },
      {
        test: {
          name: "Two",
          root: "./packages/two",
        },
      },
    ],
  },
});
> vitest --run --coverage

 RUN  v4.0.16 /x/examples/packages/vitest-example
      Coverage enabled with v8

 ✓  Two  test/get-user.test.ts (1 test) 1ms
 ✓  One  test/math.test.ts (1 test) 1ms

 Test Files  2 passed (2)
      Tests  2 passed (2)
   Start at  10:12:31
   Duration  115ms (transform 32ms, setup 0ms, import 43ms, tests 2ms, environment 0ms)

 % Coverage report from v8
--------------|---------|----------|---------|---------|-------------------
File          | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
--------------|---------|----------|---------|---------|-------------------
All files     |      40 |      100 |      40 |      40 |                   
 one/src      |      25 |      100 |      25 |      25 |                   
  math.ts     |      25 |      100 |      25 |      25 | 6-14              
 two/src      |     100 |      100 |     100 |     100 |                   
  get-user.ts |     100 |      100 |     100 |     100 |                   
--------------|---------|----------|---------|---------|-------------------

This should show coverage for packages/one, but it's missing:

> vitest --run --coverage --project one

 RUN  v4.0.16 /x/examples/packages/vitest-example
      Coverage enabled with v8

 ✓  One  test/math.test.ts (1 test) 1ms
   ✓ sum 0ms

 Test Files  1 passed (1)
      Tests  1 passed (1)
   Start at  10:12:50
   Duration  99ms (transform 14ms, setup 0ms, import 19ms, tests 1ms, environment 0ms)

 % Coverage report from v8
----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |       0 |        0 |       0 |       0 |                   
----------|---------|----------|---------|---------|-------------------

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, I will evaluate these cases.

const matchTarget = isExternal ? filename : relativePath

this.globCache.set(filename, included)
if (excludes.length && pm.isMatch(matchTarget, excludes, { dot: true })) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

excludes is always defined array.

Suggested change
if (excludes.length && pm.isMatch(matchTarget, excludes, { dot: true })) {
if (pm.isMatch(matchTarget, excludes, { dot: true })) {

continue
}

if (pm.isMatch(matchTarget, includeGlobs, { dot: true, contains: true })) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need 2x pm.isMatch calls, instead of doing just one with passing ignore: options.exclude? Any examples that would fail without 2x calls?

Copy link
Contributor Author

@DevJoaoLopes DevJoaoLopes Jan 18, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AriPerkkio

You’re right that we call pm.isMatch twice, but they serve different purposes and need distinct options:

First call (excludes, { dot: true }): early-out for any path matching coverage.exclude, regardless of how includes are written. This prevents excluded files from slipping through when an include pattern is broad.
Second call (includeGlobs, { dot: true, contains: true }): only after passing exclusion do we check if the file qualifies for coverage.include. The contains: true is important for patterns like "src/utils" that should match nested paths (e.g., src/utils/math.ts), which a strict match would miss.
Dropping either call breaks behavior: without the exclude check, excluded files (e.g., __mocks__) get counted; without the include check (with contains: true), legitimate files under broad includes are skipped.

Comment on lines 8 to 14
include: [normalizeURL(import.meta.url)],
coverage: {
reporter: 'json',
exclude: ['./utils.ts'],
exclude: ['./utils.ts', '**/test/**'],
},
})

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like you needed to add **/test/** here to avoid test/coverage-test/test/bundled-sources.test.ts being showed up here. I think that's actually bug.

Debugging this case further shows that isIncluded is falsely returning true for isIncluded('/x/vitest/test/coverage-test/test/bundled-sources.test.ts') even when this.options.excludes contains following:

[
  './utils.ts',
  '/x/vitest/test/coverage-test/test/bundled-sources.test.ts',
  '/x/vitest/test/coverage-test/fixtures/configs/vitest.config.ts',
  'vitest.config.ts',
  'vitest.config.mts',
  'vitest.config.cts',
  'vitest.config.js',
  'vitest.config.mjs',
  'vitest.config.cjs',
  'vite.config.ts',
  'vite.config.mts',
  'vite.config.cts',
  'vite.config.js',
  'vite.config.mjs',
  'vite.config.cjs',
  '**/virtual:*',
  '**/__x00__*',
  '**/node_modules/**'
]
Suggested change
include: [normalizeURL(import.meta.url)],
coverage: {
reporter: 'json',
exclude: ['./utils.ts'],
exclude: ['./utils.ts', '**/test/**'],
},
})
exclude: ['./utils.ts'],

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Following the suggestion below, I'm getting a timeout error:

await runVitest({
    // include: [normalizeURL(import.meta.url)],
    // coverage: {
    //   reporter: 'json',
    //   exclude: ['./utils.ts', '**/test/**'],
    // },
    exclude: ['./utils.ts'],
  })

Error:

image

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't remove include and coverage, just change the coverage.exclude back to exclude: ['./utils.ts'].

@DevJoaoLopes DevJoaoLopes force-pushed the fix/coverage-include-exclude-not-work branch from dab0aa3 to c98cb54 Compare January 19, 2026 07:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Options coverage.include and coverage.exclude do not work as expected

2 participants