Skip to content

Commit

Permalink
chore: return "outputDiffLines" option
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Mar 7, 2023
1 parent ce81508 commit 8a43fb2
Show file tree
Hide file tree
Showing 7 changed files with 59 additions and 12 deletions.
19 changes: 19 additions & 0 deletions docs/config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,25 @@ Custom reporters for output. Reporters can be [a Reporter instance](https://gith
- `'hanging-process'` - displays a list of hanging processes, if Vitest cannot exit process safely. This might be a heavy operation, enable it only if Vitest consistently cannot exit process
- path of a custom reporter (e.g. `'./path/to/reporter.ts'`, `'@scope/reporter'`)

### outputDiffLines

- **Type:** `number`
- **Default:** `15`
- **CLI:** `--outputDiffLines=<lines>`, `--output-diff-lines=<lines>`

Limit the number of single output diff lines up to `15`. Vitest counts all `+-` lines when determining when to stop. For example, you might see diff like this, if you set this property to `3`:

```diff
- test: 1,
+ test: 2,
- obj: '1',
...
- test2: 1,
+ test2: 1,
- obj2: '2',
...
```

### outputFile

- **Type:** `string | Record<string, string>`
Expand Down
1 change: 1 addition & 0 deletions docs/guide/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ export default {
| `--silent` | Silent console output from tests |
| `--isolate` | Isolate environment for each test file (default: `true`) |
| `--reporter <name>` | Select reporter: `default`, `verbose`, `dot`, `junit`, `json`, or a path to a custom reporter |
| `--outputDiffLines <lines>` | Limit number of output diff lines up to `<lines>`. |
| `--outputFile <filename/-s>` | Write test results to a file when the `--reporter=json` or `--reporter=junit` option is also specified <br /> Via [cac's dot notation] you can specify individual outputs for multiple reporters |
| `--coverage` | Enable coverage report |
| `--run` | Do not watch |
Expand Down
12 changes: 6 additions & 6 deletions packages/runner/src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,15 +150,15 @@ export async function runTest(test: Test, runner: VitestRunner) {
test.result.state = 'pass'
}
catch (e) {
failTask(test.result, e)
failTask(test.result, e, runner)
}

try {
await callSuiteHook(test.suite, test, 'afterEach', runner, [test.context, test.suite])
await callCleanupHooks(beforeEachCleanups)
}
catch (e) {
failTask(test.result, e)
failTask(test.result, e, runner)
}

if (test.result.state === 'pass')
Expand Down Expand Up @@ -195,9 +195,9 @@ export async function runTest(test: Test, runner: VitestRunner) {
updateTask(test, runner)
}

function failTask(result: TaskResult, err: unknown) {
function failTask(result: TaskResult, err: unknown, runner: VitestRunner) {
result.state = 'fail'
const error = processError(err)
const error = processError(err, runner.config)
result.error = error
result.errors ??= []
result.errors.push(error)
Expand Down Expand Up @@ -268,15 +268,15 @@ export async function runSuite(suite: Suite, runner: VitestRunner) {
}
}
catch (e) {
failTask(suite.result, e)
failTask(suite.result, e, runner)
}

try {
await callSuiteHook(suite, suite, 'afterAll', runner, [suite])
await callCleanupHooks(beforeAllCleanups)
}
catch (e) {
failTask(suite.result, e)
failTask(suite.result, e, runner)
}
}

Expand Down
1 change: 1 addition & 0 deletions packages/runner/src/types/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface VitestRunnerConfig {
seed?: number
hooks: SequenceHooks
}
outputDiffLines?: number
maxConcurrency: number
testTimeout: number
hookTimeout: number
Expand Down
5 changes: 3 additions & 2 deletions packages/runner/src/utils/error.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { deepClone, format, getOwnProperties, getType } from '@vitest/utils'
import type { DiffOptions } from '@vitest/utils/diff'
import { unifiedDiff } from '@vitest/utils/diff'

export interface ParsedStack {
Expand Down Expand Up @@ -104,7 +105,7 @@ function normalizeErrorMessage(message: string) {
return message.replace(/__vite_ssr_import_\d+__\./g, '')
}

export function processError(err: any) {
export function processError(err: any, options: DiffOptions = {}) {
if (!err || typeof err !== 'object')
return err
// stack is not serialized in worker communication
Expand All @@ -120,7 +121,7 @@ export function processError(err: any) {
const { replacedActual, replacedExpected } = replaceAsymmetricMatcher(clonedActual, clonedExpected)

if (err.showDiff || (err.showDiff === undefined && err.expected !== undefined && err.actual !== undefined))
err.diff = unifiedDiff(replacedActual, replacedExpected)
err.diff = unifiedDiff(replacedActual, replacedExpected, options)

// some Error implementations don't allow rewriting message
try {
Expand Down
27 changes: 23 additions & 4 deletions packages/utils/src/diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { diffDescriptors, getConcordanceTheme } from './descriptors'

export interface DiffOptions {
showLegend?: boolean
outputDiffLines?: number
}

/**
Expand All @@ -17,7 +18,7 @@ export function unifiedDiff(actual: unknown, expected: unknown, options: DiffOpt
const theme = getConcordanceTheme()
const diff = diffDescriptors(actual, expected, { theme })

const { showLegend = true } = options
const { showLegend = true, outputDiffLines = 15 } = options

const counts = {
'+': 0,
Expand All @@ -28,11 +29,16 @@ export function unifiedDiff(actual: unknown, expected: unknown, options: DiffOpt
const minus = ` ${c.green('+')}`

const lines = diff.split(/\r?\n/g)
lines.forEach((line) => {
if (line.startsWith(plus))
let firstErrorLine: number | null = null
lines.forEach((line, index) => {
if (line.startsWith(plus)) {
firstErrorLine ??= index
counts['+']++
else if (line.startsWith(minus))
}
else if (line.startsWith(minus)) {
firstErrorLine ??= index
counts['-']++
}
})
const isCompact = counts['+'] === 1 && counts['-'] === 1 && lines.length === 2

Expand All @@ -50,5 +56,18 @@ export function unifiedDiff(actual: unknown, expected: unknown, options: DiffOpt
}
}

if (firstErrorLine != null && outputDiffLines) {
const start = Math.max(0, firstErrorLine - 1)
const end = Math.min(lines.length, firstErrorLine + outputDiffLines)
const linesAfterCount = lines.length - end

const linesBefore = start ? ` ${c.gray(`... ${start} more line${start > 1 ? 's' : ''}\n`)}` : ''
const linesAfter = linesAfterCount ? `\n ${c.gray(`... ${linesAfterCount} more line${linesAfterCount > 1 ? 's' : ''}\n`)}` : ''
const diffOutput = lines.slice(start, end).map(line => line.replace(/␊\s*$/, '')).join('\n')
const helperBunner = linesAfter && (counts['+'] + counts['-'] > outputDiffLines) ? `\n Use ${c.gray('test.outputDiffLines')} to increase the number of lines shown.` : ''

return legend + linesBefore + diffOutput + linesAfter + helperBunner
}

return legend + diff
}
6 changes: 6 additions & 0 deletions packages/vitest/src/types/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,12 @@ export interface InlineConfig {
*/
reporters?: Arrayable<BuiltinReporters | 'html' | Reporter | Omit<string, BuiltinReporters>>

/**
* Maximum number of line to show in a single diff.
* @default 15
*/
outputDiffLines?: number

/**
* Write test results to a file when the --reporter=json` or `--reporter=junit` option is also specified.
* Also definable individually per reporter by using an object instead.
Expand Down

0 comments on commit 8a43fb2

Please sign in to comment.