-
Notifications
You must be signed in to change notification settings - Fork 498
/
Copy pathsingle-screenshot-assertion-per-test.ts
85 lines (76 loc) · 2.48 KB
/
single-screenshot-assertion-per-test.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
76
77
78
79
80
81
82
83
84
85
// Copyright 2023 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import {createRule} from './utils/ruleCreator.ts';
export default createRule({
name: 'single-screenshot-assertion-per-test',
meta: {
type: 'problem',
docs: {
description: 'prevent submitting with variables set to true or false',
category: 'Possible Errors',
},
messages: {
moreThanOneScreenshotAssertionFound: 'A test must only have a single screenshot assertion inside.',
},
fixable: 'code',
schema: [] // no options
},
defaultOptions: [],
create: function(context) {
function nodeIsFunctionCallToCheck(node) {
if (node.expression.type === 'CallExpression') {
return true;
}
if (node.expression.type === 'AwaitExpression') {
return node.expression.argument.type === 'CallExpression';
}
return false;
}
function countScreenshotAssertions(functionBodyNodes) {
const assertionCalls = functionBodyNodes.filter(node => {
if (node.type !== 'ExpressionStatement') {
return false;
}
if (!nodeIsFunctionCallToCheck(node)) {
return false;
}
let nameOfCalledFunction = '';
if (node.expression.type === 'CallExpression') {
nameOfCalledFunction = node.expression.callee.name;
} else if (node.expression.type === 'AwaitExpression') {
nameOfCalledFunction = node.expression.argument.callee.name;
}
if (nameOfCalledFunction === '') {
throw new Error('Could not find name of called function.');
}
return ['assertElementScreenshotUnchanged', 'assertPageScreenshotUnchanged'].includes(nameOfCalledFunction);
});
return assertionCalls.length;
}
function checkFunctionNode(node) {
const bodyNodes = node.body?.body;
if (!bodyNodes || bodyNodes.length === 0) {
return;
}
const totalScreenshotAssertions = countScreenshotAssertions(bodyNodes);
if (totalScreenshotAssertions > 1) {
context.report({
node,
messageId: 'moreThanOneScreenshotAssertionFound',
});
}
}
return {
ArrowFunctionExpression(node) {
checkFunctionNode(node);
},
FunctionExpression(node) {
checkFunctionNode(node);
},
FunctionDeclaration(node) {
checkFunctionNode(node);
}
};
}
});