Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add possibility to filter test files by fileName #1915

Merged
merged 3 commits into from Sep 1, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 27 additions & 0 deletions docs/config/index.md
Expand Up @@ -553,6 +553,33 @@ test('doNotRun', () => {
})
```

### fileNamePattern

- **Type** `string`

Run test files matching the pattern.
If you add `Reducer` to this property, it will run test files matching this pattern.

```js
// fileName: UserReducer.test.ts
import { expect, test } from 'vitest'

// run
test('test inside UserReducer.test.ts', () => {
expect(true).toBe(true)
})
```

```js
// fileName: UserService.test.ts
import { expect, test } from 'vitest'

// skipped
test('test inside UserService.test.ts', () => {
expect(true).toBe(true)
})
```

### open

- **Type:** `boolean`
Expand Down
1 change: 1 addition & 0 deletions docs/guide/cli.md
Expand Up @@ -50,6 +50,7 @@ vitest related /src/index.ts /src/hello-world.js
| `-u, --update` | Update snapshots |
| `-w, --watch` | Smart & instant watch mode |
| `-t, --testNamePattern <pattern>` | Run tests with full names matching the pattern |
| `-p, --fileNamePattern <pattern>` | Run test files matching the pattern |
| `--dir <path>`| Base directory to scan for the test files |
| `--ui` | Enable UI |
| `--open` | Open the UI automatically if enabled (default: `true`) |
Expand Down
1 change: 1 addition & 0 deletions packages/vitest/src/node/cli.ts
Expand Up @@ -14,6 +14,7 @@ cli
.option('-u, --update', 'update snapshot')
.option('-w, --watch', 'watch mode')
.option('-t, --testNamePattern <pattern>', 'run tests with full names matching the specified pattern')
.option('-p, --fileNamePattern <pattern>', 'run test files matching the pattern')
.option('--dir <path>', 'base directory to scan for the test files')
.option('--ui', 'enable UI')
.option('--open', 'open UI automatically (default: !process.env.CI))')
Expand Down
5 changes: 5 additions & 0 deletions packages/vitest/src/node/core.ts
Expand Up @@ -301,6 +301,11 @@ export class Vitest {
await this.rerunFiles(files, trigger)
}

async changeFilenamePattern(pattern: string, files: string[] = this.state.getFilepaths().filter(f => f.includes(pattern)), trigger?: string) {
this.config.fileNamePattern = pattern
await this.rerunFiles(files, trigger)
}

async rerunFailed() {
await this.rerunFiles(this.state.getFailedFilepaths(), 'rerun failed')
}
Expand Down
16 changes: 16 additions & 0 deletions packages/vitest/src/node/stdin.ts
Expand Up @@ -8,6 +8,7 @@ const keys = [
['a', 'rerun all tests'],
['f', 'rerun only failed tests'],
['u', 'update snapshot'],
['p', 'filter by a filename regex pattern'],
sheremet-va marked this conversation as resolved.
Show resolved Hide resolved
['t', 'filter by a test name regex pattern'],
['q', 'quit'],
]
Expand Down Expand Up @@ -48,6 +49,9 @@ export function registerConsoleShortcuts(ctx: Vitest) {
// change testNamePattern
if (name === 't')
return inputNamePattern()
// change fileNamePattern
if (name === 'p')
return inputFilePattern()
// quit
if (name === 'q')
return ctx.exit(true)
Expand All @@ -69,6 +73,18 @@ export function registerConsoleShortcuts(ctx: Vitest) {
on()
}

async function inputFilePattern() {
off()
const { filter = '' }: { filter: string } = await prompt([{
name: 'filter',
type: 'text',
message: 'Input filename pattern',
initial: String(ctx.config.fileNamePattern || ''),
}])
await ctx.changeFilenamePattern(filter, undefined, 'change filename pattern')
on()
}

let rl: readline.Interface | undefined
function on() {
off()
Expand Down
12 changes: 10 additions & 2 deletions packages/vitest/src/runtime/collect.ts
Expand Up @@ -22,7 +22,6 @@ function hash(str: string): string {

export async function collectTests(paths: string[], config: ResolvedConfig) {
const files: File[] = []

const browserHashMap = getWorkerState().browserHashMap!

async function importFromBrowser(filepath: string) {
Expand All @@ -34,7 +33,7 @@ export async function collectTests(paths: string[], config: ResolvedConfig) {
return await import(`${filepath}?v=${hash}`)
}

for (const filepath of paths) {
for (const filepath of matchPattern(paths, config.fileNamePattern)) {
sheremet-va marked this conversation as resolved.
Show resolved Hide resolved
const path = relativePath(config.root, filepath)
const file: File = {
id: hash(path),
Expand Down Expand Up @@ -137,6 +136,15 @@ function interpretTaskModes(suite: Suite, namePattern?: string | RegExp, onlyMod
suite.mode = 'skip'
}
}
/**
* Skip files that are not matched by the pattern.
*/
function matchPattern(files: string[], pattern = '') {
if (!pattern)
return files

return files.filter(f => f.includes(pattern))
}

function getTaskFullName(task: TaskBase): string {
return `${task.suite ? `${getTaskFullName(task.suite)} ` : ''}${task.name}`
Expand Down
7 changes: 6 additions & 1 deletion packages/vitest/src/types/config.ts
Expand Up @@ -249,6 +249,10 @@ export interface InlineConfig {
*/
testNamePattern?: string | RegExp

/**
* run test files with the specified pattern
*/
fileNamePattern?: string
/**
* Will call `.mockClear()` on all spies before each test
* @default false
Expand Down Expand Up @@ -470,12 +474,13 @@ export interface UserConfig extends InlineConfig {
shard?: string
}

export interface ResolvedConfig extends Omit<Required<UserConfig>, 'config' | 'filters' | 'coverage' | 'testNamePattern' | 'related' | 'api' | 'reporters' | 'resolveSnapshotPath' | 'shard' | 'cache' | 'sequence'> {
export interface ResolvedConfig extends Omit<Required<UserConfig>, 'config' | 'filters' | 'coverage' | 'testNamePattern' | 'fileNamePattern' | 'related' | 'api' | 'reporters' | 'resolveSnapshotPath' | 'shard' | 'cache' | 'sequence'> {
base?: string

config?: string
filters?: string[]
testNamePattern?: RegExp
fileNamePattern?: string
related?: string[]

coverage: ResolvedCoverageOptions
Expand Down
7 changes: 7 additions & 0 deletions test/core/test-skip/file-name-pattern.test.ts
@@ -0,0 +1,7 @@
import { assert, describe, it } from 'vitest'

describe('fileNamePattern', () => {
it('should be filtered by fileNamePattern', () => {
assert.fail('unmatched test was included')
})
})
1 change: 1 addition & 0 deletions test/core/vitest.config.ts
Expand Up @@ -42,6 +42,7 @@ export default defineConfig({
'./test/setup.ts',
],
testNamePattern: '^((?!does not include test that).)*$',
fileNamePattern: '/core/test/',
coverage: {
provider: 'istanbul',
reporter: ['text', 'html'],
Expand Down