eslint-plugin-jest-dom 3.9.1 → 3.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.getInnerNodeFrom = getInnerNodeFrom;
7
+ exports.getAssignmentForIdentifier = getAssignmentForIdentifier;
8
+ exports.getQueryNodeFrom = getQueryNodeFrom;
9
+
10
+ var _queries = require("./queries");
11
+
12
+ /**
13
+ * Gets the inner relevant node (CallExpression, Identity, et al.) given a generic expression node
14
+ * await someAsyncFunc() => someAsyncFunc()
15
+ * someElement as HTMLDivElement => someElement
16
+ *
17
+ * @param {Object} expression - An expression node
18
+ * @returns {Object} - A node
19
+ */
20
+ function getInnerNodeFrom(expression) {
21
+ switch (expression.type) {
22
+ case "TSAsExpression":
23
+ return getInnerNodeFrom(expression.expression);
24
+
25
+ case "AwaitExpression":
26
+ return getInnerNodeFrom(expression.argument);
27
+
28
+ case "MemberExpression":
29
+ return getInnerNodeFrom(expression.object);
30
+
31
+ default:
32
+ return expression;
33
+ }
34
+ }
35
+ /**
36
+ * Get the node corresponding to the latest assignment to a variable named `identifierName`
37
+ *
38
+ * @param {Object} context - Context for a rule
39
+ * @param {String} identifierName - Name of an identifier
40
+ * @returns {Object} - A node, possibly undefined
41
+ */
42
+
43
+
44
+ function getAssignmentForIdentifier(context, identifierName) {
45
+ const variable = context.getScope().set.get(identifierName);
46
+ if (!variable) return;
47
+ const init = variable.defs[0].node.init;
48
+ let assignmentNode;
49
+
50
+ if (init) {
51
+ // let foo = bar;
52
+ assignmentNode = getInnerNodeFrom(init);
53
+ } else {
54
+ // let foo;
55
+ // foo = bar;
56
+ const assignmentRef = variable.references.reverse().find(ref => !!ref.writeExpr);
57
+
58
+ if (!assignmentRef) {
59
+ return;
60
+ }
61
+
62
+ assignmentNode = getInnerNodeFrom(assignmentRef.writeExpr);
63
+ }
64
+
65
+ return assignmentNode;
66
+ }
67
+ /**
68
+ * get query node, arg and isDTLQuery flag for a given node. useful for rules that you only
69
+ * want to apply to dom elements.
70
+ *
71
+ * @param {Object} context - Context for a rule
72
+ * @param {Object} nodeWithValueProp - AST Node to get the query from
73
+ * @returns {Object} - Object with query, queryArg & isDTLQuery
74
+ */
75
+
76
+
77
+ function getQueryNodeFrom(context, nodeWithValueProp) {
78
+ const queryNode = nodeWithValueProp.type === "Identifier" ? getAssignmentForIdentifier(context, nodeWithValueProp.name) : getInnerNodeFrom(nodeWithValueProp);
79
+
80
+ if (!queryNode || !queryNode.callee) {
81
+ return {
82
+ isDTLQuery: false,
83
+ query: null,
84
+ queryArg: null
85
+ };
86
+ }
87
+
88
+ const query = queryNode.callee.name || queryNode.callee.property.name;
89
+ const queryArg = queryNode.arguments[0] && queryNode.arguments[0].value;
90
+
91
+ const isDTLQuery = _queries.queries.includes(query);
92
+
93
+ return {
94
+ queryArg,
95
+ query,
96
+ isDTLQuery
97
+ };
98
+ }
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+
8
+ var _assignmentAst = require("./assignment-ast");
9
+
10
+ var _default = ({
11
+ preferred,
12
+ negatedPreferred,
13
+ attributes
14
+ }) => context => {
15
+ const getCorrectFunctionFor = (node, negated = false) => (node.arguments.length === 1 || node.arguments[1].value === true || node.arguments[1].type !== "Literal" || typeof node.arguments[1].value === "string" && node.arguments[1].value.toLowerCase() === "true" || node.arguments[1].value === "") && !negated ? preferred : negatedPreferred;
16
+
17
+ const isBannedArg = node => node.arguments.length && attributes.some(attr => attr === node.arguments[0].value); //expect(el).not.toBeEnabled() => expect(el).toBeDisabled()
18
+
19
+
20
+ return {
21
+ [`CallExpression[callee.property.name=/${preferred}|${negatedPreferred}/][callee.object.property.name='not'][callee.object.object.callee.name='expect']`](node) {
22
+ if (!negatedPreferred.startsWith("toBe")) {
23
+ return;
24
+ }
25
+
26
+ const incorrectFunction = node.callee.property.name;
27
+ const correctFunction = incorrectFunction === preferred ? negatedPreferred : preferred;
28
+ context.report({
29
+ message: `Use ${correctFunction}() instead of not.${incorrectFunction}()`,
30
+ node,
31
+ fix: fixer => fixer.replaceTextRange([node.callee.object.property.range[0], node.range[1]], `${correctFunction}()`)
32
+ });
33
+ },
34
+
35
+ //expect(getByText('foo').<attribute>).toBeTruthy()
36
+ "CallExpression[callee.property.name=/toBe(Truthy|Falsy)?|toEqual/][callee.object.callee.name='expect']"(node) {
37
+ if (!node.callee.object.arguments.length) {
38
+ return;
39
+ }
40
+
41
+ const {
42
+ arguments: [{
43
+ object,
44
+ property,
45
+ property: {
46
+ name
47
+ } = {}
48
+ }]
49
+ } = node.callee.object;
50
+ const matcher = node.callee.property.name;
51
+ const matcherArg = node.arguments.length && node.arguments[0].value;
52
+
53
+ if (!attributes.some(attr => attr === name)) {
54
+ return;
55
+ }
56
+
57
+ const {
58
+ isDTLQuery
59
+ } = (0, _assignmentAst.getQueryNodeFrom)(context, node.callee.object.arguments[0]);
60
+ if (!isDTLQuery) return;
61
+ const isNegated = matcher.endsWith("Falsy") || (matcher === "toBe" || matcher === "toEqual") && matcherArg !== true;
62
+ const correctFunction = getCorrectFunctionFor(node.callee.object, isNegated);
63
+ context.report({
64
+ node,
65
+ message: `Use ${correctFunction}() instead of checking .${name} directly`,
66
+ fix: fixer => [fixer.removeRange([object.range[1], property.range[1]]), fixer.replaceTextRange([node.callee.property.range[0], node.range[1]], `${correctFunction}()`)]
67
+ });
68
+ },
69
+
70
+ "CallExpression[callee.property.name=/toHaveProperty|toHaveAttribute/][callee.object.property.name='not'][callee.object.object.callee.name='expect']"(node) {
71
+ if (!isBannedArg(node)) {
72
+ return;
73
+ }
74
+
75
+ const arg = node.arguments[0].value;
76
+ const correctFunction = getCorrectFunctionFor(node, true);
77
+ const incorrectFunction = node.callee.property.name;
78
+ context.report({
79
+ message: `Use ${correctFunction}() instead of not.${incorrectFunction}('${arg}')`,
80
+ node,
81
+ fix: fixer => fixer.replaceTextRange([node.callee.object.property.range[0], node.range[1]], `${correctFunction}()`)
82
+ });
83
+ },
84
+
85
+ "CallExpression[callee.object.callee.name='expect'][callee.property.name=/toHaveProperty|toHaveAttribute/]"(node) {
86
+ if (!isBannedArg(node)) {
87
+ return;
88
+ }
89
+
90
+ const {
91
+ isDTLQuery
92
+ } = (0, _assignmentAst.getQueryNodeFrom)(context, node.callee.object.arguments[0]);
93
+ if (!isDTLQuery) return;
94
+ const correctFunction = getCorrectFunctionFor(node);
95
+ const incorrectFunction = node.callee.property.name;
96
+ const message = `Use ${correctFunction}() instead of ${incorrectFunction}(${node.arguments.map(({
97
+ raw,
98
+ name
99
+ }) => raw || name).join(", ")})`;
100
+ const secondArgIsLiteral = node.arguments.length === 2 && node.arguments[1].type === "Literal";
101
+ context.report({
102
+ node: node.callee.property,
103
+ message,
104
+ fix: fixer => {
105
+ if (node.arguments.length === 1 || secondArgIsLiteral) {
106
+ return [fixer.replaceTextRange([node.callee.property.range[0], node.range[1]], `${correctFunction}()`)];
107
+ }
108
+
109
+ return null;
110
+ }
111
+ });
112
+ }
113
+
114
+ };
115
+ };
116
+
117
+ exports.default = _default;
package/dist/index.js ADDED
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.configs = exports.generateAllRulesConfig = exports.generateRecommendedConfig = exports.rules = void 0;
9
+
10
+ var _requireindex = _interopRequireDefault(require("requireindex"));
11
+
12
+ /**
13
+ * @fileoverview lint rules for use with jest-dom
14
+ * @author Ben Monro
15
+ */
16
+ //------------------------------------------------------------------------------
17
+ // Requirements
18
+ //------------------------------------------------------------------------------
19
+ //------------------------------------------------------------------------------
20
+ // Plugin Definition
21
+ //------------------------------------------------------------------------------
22
+ // import all rules in src/rules
23
+ const rules = (0, _requireindex.default)(`${__dirname}/rules`);
24
+ exports.rules = rules;
25
+
26
+ const generateRecommendedConfig = allRules => Object.entries(allRules).reduce((memo, [name, rule]) => ({ ...memo,
27
+ ...(rule.meta.docs.recommended ? {
28
+ [`jest-dom/${name}`]: "error"
29
+ } : {})
30
+ }), {});
31
+
32
+ exports.generateRecommendedConfig = generateRecommendedConfig;
33
+
34
+ const generateAllRulesConfig = allRules => Object.entries(allRules).reduce((memo, [name]) => ({ ...memo,
35
+ ...{
36
+ [`jest-dom/${name}`]: "error"
37
+ }
38
+ }), {});
39
+
40
+ exports.generateAllRulesConfig = generateAllRulesConfig;
41
+ const configs = {
42
+ recommended: {
43
+ plugins: ["jest-dom"],
44
+ rules: generateRecommendedConfig(rules)
45
+ },
46
+ all: {
47
+ plugins: ["jest-dom"],
48
+ rules: generateAllRulesConfig(rules)
49
+ }
50
+ };
51
+ exports.configs = configs;
@@ -0,0 +1,11 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.queries = void 0;
7
+
8
+ var _dom = require("@testing-library/dom");
9
+
10
+ const queries = Object.keys(_dom.queries);
11
+ exports.queries = queries;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.create = exports.meta = void 0;
9
+
10
+ var _createBannedAttributeRule = _interopRequireDefault(require("../createBannedAttributeRule"));
11
+
12
+ /**
13
+ * @fileoverview prefer toBeDisabled or toBeEnabled over attribute checks
14
+ * @author Ben Monro
15
+ */
16
+ const meta = {
17
+ docs: {
18
+ description: "prefer toBeChecked over checking attributes",
19
+ category: "Best Practices",
20
+ recommended: true,
21
+ url: "prefer-checked"
22
+ },
23
+ fixable: "code"
24
+ };
25
+ exports.meta = meta;
26
+ const create = (0, _createBannedAttributeRule.default)({
27
+ preferred: "toBeChecked",
28
+ negatedPreferred: "not.toBeChecked",
29
+ attributes: ["checked", "aria-checked"]
30
+ });
31
+ exports.create = create;
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.create = exports.meta = void 0;
7
+
8
+ /**
9
+ * @fileoverview Prefer toBeEmpty over checking innerHTML
10
+ * @author Ben Monro
11
+ */
12
+ const meta = {
13
+ docs: {
14
+ description: "Prefer toBeEmpty over checking innerHTML",
15
+ category: "Best Practices",
16
+ recommended: true,
17
+ url: "prefer-empty"
18
+ },
19
+ fixable: "code" // or "code" or "whitespace"
20
+
21
+ };
22
+ exports.meta = meta;
23
+
24
+ const create = context => {
25
+ function isNonEmptyStringOrTemplateLiteral(node) {
26
+ return !['""', "''", "``", "null"].includes(context.getSourceCode().getText(node));
27
+ }
28
+
29
+ return {
30
+ [`BinaryExpression[left.property.name='innerHTML'][right.value=''][parent.callee.name='expect'][parent.parent.property.name=/toBe$|to(Strict)?Equal/]`](node) {
31
+ context.report({
32
+ node,
33
+ message: "Use toBeEmptyDOMElement instead of checking inner html.",
34
+ fix: fixer => [fixer.removeRange([node.left.object.range[1], node.range[1]]), fixer.replaceText(node.parent.parent.property, Boolean(node.parent.parent.parent.arguments[0].value) === node.operator.startsWith("=") // binary expression XNOR matcher boolean
35
+ ? "toBeEmptyDOMElement" : "not.toBeEmptyDOMElement"), fixer.remove(node.parent.parent.parent.arguments[0])]
36
+ });
37
+ },
38
+
39
+ [`BinaryExpression[left.property.name='firstChild'][right.value=null][parent.callee.name='expect'][parent.parent.property.name=/toBe$|to(Strict)?Equal/]`](node) {
40
+ context.report({
41
+ node,
42
+ message: "Use toBeEmptyDOMElement instead of checking inner html.",
43
+ fix: fixer => [fixer.removeRange([node.left.object.range[1], node.range[1]]), fixer.replaceText(node.parent.parent.property, Boolean(node.parent.parent.parent.arguments[0].value) === node.operator.startsWith("=") // binary expression XNOR matcher boolean
44
+ ? "toBeEmptyDOMElement" : "not.toBeEmptyDOMElement"), fixer.remove(node.parent.parent.parent.arguments[0])]
45
+ });
46
+ },
47
+
48
+ [`MemberExpression[property.name = 'innerHTML'][parent.callee.name = 'expect'][parent.parent.property.name = /toBe$|to(Strict)?Equal/]`](node) {
49
+ const args = node.parent.parent.parent.arguments[0];
50
+
51
+ if (isNonEmptyStringOrTemplateLiteral(args)) {
52
+ return;
53
+ }
54
+
55
+ context.report({
56
+ node,
57
+ message: "Use toBeEmptyDOMElement instead of checking inner html.",
58
+ fix: fixer => [fixer.removeRange([node.object.range[1], node.property.range[1]]), fixer.replaceText(node.parent.parent.property, "toBeEmptyDOMElement"), fixer.remove(node.parent.parent.parent.arguments[0])]
59
+ });
60
+ },
61
+
62
+ [`MemberExpression[property.name='innerHTML'][parent.parent.property.name='not'][parent.parent.parent.property.name=/toBe$|to(Strict)?Equal$/][parent.parent.object.callee.name='expect']`](node) {
63
+ const args = node.parent.parent.parent.parent.arguments[0];
64
+
65
+ if (isNonEmptyStringOrTemplateLiteral(args)) {
66
+ return;
67
+ }
68
+
69
+ context.report({
70
+ node,
71
+ message: "Use toBeEmptyDOMElement instead of checking inner html.",
72
+ fix: fixer => [fixer.removeRange([node.object.range[1], node.property.range[1]]), fixer.replaceText(node.parent.parent.parent.property, "toBeEmptyDOMElement"), fixer.remove(node.parent.parent.parent.parent.arguments[0])]
73
+ });
74
+ },
75
+
76
+ [`MemberExpression[property.name = 'firstChild'][parent.callee.name = 'expect'][parent.parent.property.name = /toBeNull$/]`](node) {
77
+ context.report({
78
+ node,
79
+ message: "Use toBeEmptyDOMElement instead of checking inner html.",
80
+ fix: fixer => [fixer.removeRange([node.object.range[1], node.property.range[1]]), fixer.replaceText(node.parent.parent.property, "toBeEmptyDOMElement")]
81
+ });
82
+ },
83
+
84
+ [`MemberExpression[property.name='firstChild'][parent.parent.property.name='not'][parent.parent.parent.property.name=/toBe$|to(Strict)?Equal$/][parent.parent.object.callee.name='expect']`](node) {
85
+ if (node.parent.parent.parent.parent.arguments[0].value !== null) {
86
+ return;
87
+ }
88
+
89
+ context.report({
90
+ node,
91
+ message: "Use toBeEmptyDOMElement instead of checking inner html.",
92
+ fix: fixer => [fixer.removeRange([node.object.range[1], node.property.range[1]]), fixer.replaceText(node.parent.parent.parent.property, "toBeEmptyDOMElement"), fixer.remove(node.parent.parent.parent.parent.arguments[0])]
93
+ });
94
+ },
95
+
96
+ [`MemberExpression[property.name='firstChild'][parent.parent.property.name='not'][parent.parent.parent.property.name=/toBeNull$/][parent.parent.object.callee.name='expect']`](node) {
97
+ context.report({
98
+ node,
99
+ message: "Use toBeEmptyDOMElement instead of checking inner html.",
100
+ fix: fixer => [fixer.removeRange([node.object.range[1], node.property.range[1]]), fixer.replaceText(node.parent.parent.parent.property, "toBeEmptyDOMElement")]
101
+ });
102
+ },
103
+
104
+ [`MemberExpression[property.name = 'firstChild'][parent.callee.name = 'expect'][parent.parent.property.name = /toBe$|to(Strict)?Equal/]`](node) {
105
+ if (node.parent.parent.parent.arguments[0].value !== null) {
106
+ return;
107
+ }
108
+
109
+ context.report({
110
+ node,
111
+ message: "Use toBeEmptyDOMElement instead of checking inner html.",
112
+ fix: fixer => [fixer.removeRange([node.object.range[1], node.property.range[1]]), fixer.replaceText(node.parent.parent.property, "toBeEmptyDOMElement"), fixer.remove(node.parent.parent.parent.arguments[0])]
113
+ });
114
+ }
115
+
116
+ };
117
+ };
118
+
119
+ exports.create = create;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+
5
+ Object.defineProperty(exports, "__esModule", {
6
+ value: true
7
+ });
8
+ exports.create = exports.meta = void 0;
9
+
10
+ var _createBannedAttributeRule = _interopRequireDefault(require("../createBannedAttributeRule"));
11
+
12
+ /**
13
+ * @fileoverview prefer toBeDisabled or toBeEnabled over attribute checks
14
+ * @author Ben Monro
15
+ */
16
+ const meta = {
17
+ docs: {
18
+ description: "prefer toBeDisabled or toBeEnabled over checking attributes",
19
+ category: "Best Practices",
20
+ recommended: true,
21
+ url: "prefer-enabled-disabled"
22
+ },
23
+ fixable: "code"
24
+ };
25
+ exports.meta = meta;
26
+ const create = (0, _createBannedAttributeRule.default)({
27
+ preferred: "toBeDisabled",
28
+ negatedPreferred: "toBeEnabled",
29
+ attributes: ["disabled"]
30
+ });
31
+ exports.create = create;
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.create = exports.meta = void 0;
7
+
8
+ /**
9
+ * @fileoverview prefer toHaveFocus over checking activeElementa
10
+ * @author Ben Monro
11
+ */
12
+ const variantsOfDoc = [// document:
13
+ `[object.name=document]`, // window.document || global.document:
14
+ `[object.object.name=/(global|window)$/][object.property.name=document]`, // global.window.document:
15
+ `[object.object.object.name='global'][object.object.property.name='window'][object.property.name=document]`];
16
+ const meta = {
17
+ docs: {
18
+ url: "prefer-focus",
19
+ description: "prefer toHaveFocus over checking document.activeElement",
20
+ category: "Best Practices",
21
+ recommended: true
22
+ },
23
+ fixable: "code"
24
+ };
25
+ exports.meta = meta;
26
+
27
+ const create = context => ({
28
+ [variantsOfDoc.map(variant => `MemberExpression${variant}[property.name='activeElement'][parent.parent.object.callee.name='expect'][parent.parent.property.name='not'][parent.parent.parent.property.name=/to(Be|(Strict)?Equal)$/]`).join(", ")](node) {
29
+ const element = node.parent.parent.parent.parent.callee.parent.arguments[0];
30
+ const matcher = node.parent.parent.parent.parent.callee.property;
31
+ context.report({
32
+ node: node.parent,
33
+ message: `Use toHaveFocus instead of checking activeElement`,
34
+ fix: fixer => {
35
+ if (element.name) {
36
+ return [fixer.replaceText(node, element.name), fixer.remove(element), fixer.replaceText(matcher, "toHaveFocus")];
37
+ }
38
+
39
+ return [fixer.removeRange([node.range[0], element.range[0]]), fixer.insertTextAfterRange([element.range[1], element.range[1] + 1], ".not.toHaveFocus()")];
40
+ }
41
+ });
42
+ },
43
+
44
+ [variantsOfDoc.map(variant => `MemberExpression${variant}[property.name='activeElement'][parent.callee.object.object.callee.name='expect'][parent.callee.property.name=/to(Be|(Strict)?Equal)$/]`).join(", ")](node) {
45
+ const matcher = node.parent.callee.property;
46
+ context.report({
47
+ node: node.parent,
48
+ message: `Use toHaveFocus instead of checking activeElement`,
49
+ fix: fixer => [fixer.remove(node), fixer.replaceText(matcher, "toHaveFocus")]
50
+ });
51
+ },
52
+
53
+ [variantsOfDoc.map(variant => `MemberExpression${variant}[property.name='activeElement'][parent.callee.name='expect'][parent.parent.property.name=/to(Be|(Strict)?Equal)$/]`).join(", ")](node) {
54
+ const element = node.parent.parent.parent.arguments[0];
55
+ const matcher = node.parent.parent.property;
56
+ context.report({
57
+ node: node.parent,
58
+ message: `Use toHaveFocus instead of checking activeElement`,
59
+ fix: fixer => {
60
+ if (!element.name) {
61
+ return [fixer.removeRange([node.range[0], element.range[0]]), fixer.insertTextAfterRange([element.range[1], element.range[1] + 1], ".toHaveFocus()")];
62
+ }
63
+
64
+ return [fixer.replaceText(node, element.name), fixer.remove(element), fixer.replaceText(matcher, "toHaveFocus")];
65
+ }
66
+ });
67
+ },
68
+
69
+ [variantsOfDoc.map(variant => `MemberExpression${variant}[property.name='activeElement'][parent.callee.object.callee.name='expect'][parent.callee.property.name=/to(Be|(Strict)?Equal)$/]`).join(", ")](node) {
70
+ const matcher = node.parent.callee.property;
71
+ context.report({
72
+ node: node.parent,
73
+ message: `Use toHaveFocus instead of checking activeElement`,
74
+ fix: fixer => [fixer.remove(node), fixer.replaceText(matcher, "toHaveFocus")]
75
+ });
76
+ }
77
+
78
+ });
79
+
80
+ exports.create = create;