-
Notifications
You must be signed in to change notification settings - Fork 240
/
Copy pathno-large-snapshots.js
105 lines (96 loc) · 2.75 KB
/
no-large-snapshots.js
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { isAbsolute } from 'path';
import { getDocsUrl, getStringValue } from './util';
const reportOnViolation = (context, node) => {
const lineLimit =
context.options[0] && Number.isFinite(context.options[0].maxSize)
? context.options[0].maxSize
: 50;
const startLine = node.loc.start.line;
const endLine = node.loc.end.line;
const lineCount = endLine - startLine;
const whitelistedSnapshots =
context.options &&
context.options[0] &&
context.options[0].whitelistedSnapshots;
const allPathsAreAbsolute = Object.keys(whitelistedSnapshots || {}).every(
isAbsolute,
);
if (!allPathsAreAbsolute) {
throw new Error(
'All paths for whitelistedSnapshots must be absolute. You can use JS config and `path.resolve`',
);
}
let isWhitelisted = false;
if (whitelistedSnapshots) {
const fileName = context.getFilename();
const whitelistedSnapshotsInFile = whitelistedSnapshots[fileName];
if (whitelistedSnapshotsInFile) {
const snapshotName = getStringValue(node.expression.left.property);
isWhitelisted = whitelistedSnapshotsInFile.some(name => {
if (name.test && typeof name.test === 'function') {
return name.test(snapshotName);
}
return name === snapshotName;
});
}
}
if (!isWhitelisted && lineCount > lineLimit) {
context.report({
messageId: lineLimit === 0 ? 'noSnapshot' : 'tooLongSnapshots',
data: { lineLimit, lineCount },
node,
});
}
};
export default {
meta: {
docs: {
url: getDocsUrl(__filename),
},
messages: {
noSnapshot: '`{{ lineCount }}`s should begin with lowercase',
tooLongSnapshots:
'Expected Jest snapshot to be smaller than {{ lineLimit }} lines but was {{ lineCount }} lines long',
},
schema: [
{
type: 'object',
properties: {
maxSize: {
type: 'number',
},
whitelistedSnapshots: {
type: 'object',
patternProperties: {
'.*': { type: 'array' },
},
},
},
additionalProperties: false,
},
],
},
create(context) {
if (context.getFilename().endsWith('.snap')) {
return {
ExpressionStatement(node) {
reportOnViolation(context, node);
},
};
} else if (context.getFilename().endsWith('.js')) {
return {
CallExpression(node) {
const propertyName =
node.callee.property && node.callee.property.name;
if (
propertyName === 'toMatchInlineSnapshot' ||
propertyName === 'toThrowErrorMatchingInlineSnapshot'
) {
reportOnViolation(context, node);
}
},
};
}
return {};
},
};