/
check.ts
75 lines (69 loc) · 2.12 KB
/
check.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import assert from 'assert';
import { convert } from '../../src/index';
import { DEFAULT_OPTIONS, Options } from '../../src/options';
import PatchError from '../../src/utils/PatchError';
import stripSharedIndent from '../../src/utils/stripSharedIndent';
export interface Extra {
options?: Options;
shouldStripIndent?: boolean;
}
export default function check(
source: string,
expected: string,
{ options = {}, shouldStripIndent = true }: Extra = {}
): void {
({ source, expected } = maybeStripIndent(shouldStripIndent, source, expected));
checkOutput(source, expected, { ...options, useCS2: false });
checkOutput(source, expected, { ...options, useCS2: true });
}
export function checkCS1(
source: string,
expected: string,
{ options = {}, shouldStripIndent = true }: Extra = {}
): void {
({ source, expected } = maybeStripIndent(shouldStripIndent, source, expected));
checkOutput(source, expected, { ...options, useCS2: false });
}
export function checkCS2(
source: string,
expected: string,
{ options = {}, shouldStripIndent = true }: Extra = {}
): void {
({ source, expected } = maybeStripIndent(shouldStripIndent, source, expected));
checkOutput(source, expected, { ...options, useCS2: true });
}
function maybeStripIndent(
shouldStripIndent: boolean,
source: string,
expected: string
): { source: string; expected: string } {
if (shouldStripIndent) {
if (source[0] === '\n') {
source = stripSharedIndent(source);
}
if (expected[0] === '\n') {
expected = stripSharedIndent(expected);
}
}
return { source, expected };
}
function checkOutput(source: string, expected: string, options: Options): void {
try {
const converted = convert(source, {
...DEFAULT_OPTIONS,
disableSuggestionComment: true,
...options,
});
let actual = converted.code;
if (actual.endsWith('\n') && !expected.endsWith('\n')) {
actual = actual.slice(0, -1);
}
expect(actual).toBe(expected);
} catch (err: unknown) {
assert(err instanceof Error);
if (PatchError.detect(err)) {
console.error(PatchError.prettyPrint(err));
}
throw err;
}
}