eslint-plugin-jest 25.3.1 → 25.4.0

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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,33 @@
1
+ # [25.4.0](https://github.com/jest-community/eslint-plugin-jest/compare/v25.3.4...v25.4.0) (2022-01-15)
2
+
3
+
4
+ ### Features
5
+
6
+ * **prefer-expect-assertions:** support requiring only if `expect` is used in a loop ([#1013](https://github.com/jest-community/eslint-plugin-jest/issues/1013)) ([e6f4f8a](https://github.com/jest-community/eslint-plugin-jest/commit/e6f4f8aaf7664bcf9d9d5549c3c43b1b09f49461))
7
+
8
+ ## [25.3.4](https://github.com/jest-community/eslint-plugin-jest/compare/v25.3.3...v25.3.4) (2022-01-01)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * **prefer-lowercase-title:** ignore `it` and `test` separately ([#1011](https://github.com/jest-community/eslint-plugin-jest/issues/1011)) ([f1a7674](https://github.com/jest-community/eslint-plugin-jest/commit/f1a767400967bd923512f79e80f283b3b2afa772))
14
+
15
+ ## [25.3.3](https://github.com/jest-community/eslint-plugin-jest/compare/v25.3.2...v25.3.3) (2021-12-30)
16
+
17
+
18
+ ### Bug Fixes
19
+
20
+ * **prefer-to-contain:** support square bracket accessors ([#1009](https://github.com/jest-community/eslint-plugin-jest/issues/1009)) ([73984a7](https://github.com/jest-community/eslint-plugin-jest/commit/73984a79f790986a17116589a587506bcc10efc0))
21
+ * **prefer-to-have-length:** support square bracket accessors ([#1010](https://github.com/jest-community/eslint-plugin-jest/issues/1010)) ([9e70f55](https://github.com/jest-community/eslint-plugin-jest/commit/9e70f550e341432f69a1cd334c19df87513ea906))
22
+
23
+ ## [25.3.2](https://github.com/jest-community/eslint-plugin-jest/compare/v25.3.1...v25.3.2) (2021-12-27)
24
+
25
+
26
+ ### Bug Fixes
27
+
28
+ * **no-large-snapshots:** only count size of template string for inline snapshots ([#1005](https://github.com/jest-community/eslint-plugin-jest/issues/1005)) ([5bea38f](https://github.com/jest-community/eslint-plugin-jest/commit/5bea38f9773ab686f08a7cc25247a782d50aa5ed))
29
+ * **prefer-hooks-on-top:** improve message & docs ([#999](https://github.com/jest-community/eslint-plugin-jest/issues/999)) ([f9e7ae2](https://github.com/jest-community/eslint-plugin-jest/commit/f9e7ae29233daad7bfea2230bea7266659299328))
30
+
1
31
  ## [25.3.1](https://github.com/jest-community/eslint-plugin-jest/compare/v25.3.0...v25.3.1) (2021-12-27)
2
32
 
3
33
 
@@ -58,6 +58,16 @@ test('my test', () => {
58
58
 
59
59
  ## Options
60
60
 
61
+ This rule can be configured to only check tests that match certain patterns that
62
+ typically look like `expect` calls might be missed, such as in promises or
63
+ loops.
64
+
65
+ By default, none of these options are enabled meaning the rule checks _every_
66
+ test for a call to either `expect.hasAssertions` or `expect.assertions`. If any
67
+ of the options are enabled the rule checks any test that matches _at least one_
68
+ of the patterns represented by the enabled options (think "OR" rather than
69
+ "AND").
70
+
61
71
  #### `onlyFunctionsWithAsyncKeyword`
62
72
 
63
73
  When `true`, this rule will only warn for tests that use the `async` keyword.
@@ -97,3 +107,53 @@ test('my test', async () => {
97
107
  expect(result).toBe('foo');
98
108
  });
99
109
  ```
110
+
111
+ #### `onlyFunctionsWithExpectInLoop`
112
+
113
+ When `true`, this rule will only warn for tests that have `expect` calls within
114
+ a native loop.
115
+
116
+ ```json
117
+ {
118
+ "rules": {
119
+ "jest/prefer-expect-assertions": [
120
+ "warn",
121
+ { "onlyFunctionsWithAsyncKeyword": true }
122
+ ]
123
+ }
124
+ }
125
+ ```
126
+
127
+ Examples of **incorrect** code when `'onlyFunctionsWithExpectInLoop'` is `true`:
128
+
129
+ ```js
130
+ describe('getNumbers', () => {
131
+ it('only returns numbers that are greater than zero', () => {
132
+ const numbers = getNumbers();
133
+
134
+ for (const number in numbers) {
135
+ expect(number).toBeGreaterThan(0);
136
+ }
137
+ });
138
+ });
139
+ ```
140
+
141
+ Examples of **correct** code when `'onlyFunctionsWithExpectInLoop'` is `true`:
142
+
143
+ ```js
144
+ describe('getNumbers', () => {
145
+ it('only returns numbers that are greater than zero', () => {
146
+ expect.hasAssertions();
147
+
148
+ const numbers = getNumbers();
149
+
150
+ for (const number in numbers) {
151
+ expect(number).toBeGreaterThan(0);
152
+ }
153
+ });
154
+
155
+ it('returns more than one number', () => {
156
+ expect(getNumbers().length).toBeGreaterThan(1);
157
+ });
158
+ });
159
+ ```
@@ -1,6 +1,10 @@
1
1
  # Suggest having hooks before any test cases (`prefer-hooks-on-top`)
2
2
 
3
- All hooks should be defined before the start of the tests
3
+ While hooks can be setup anywhere in a test file, they are always called in a
4
+ specific order which means it can be confusing if they're intermixed with test
5
+ cases.
6
+
7
+ This rule helps to ensure that hooks are always defined before test cases.
4
8
 
5
9
  ## Rule Details
6
10
 
@@ -11,47 +15,51 @@ Examples of **incorrect** code for this rule
11
15
 
12
16
  describe('foo', () => {
13
17
  beforeEach(() => {
14
- //some hook code
15
- });
16
- test('bar', () => {
17
- some_fn();
18
+ seedMyDatabase();
18
19
  });
19
- beforeAll(() => {
20
- //some hook code
21
- });
22
- test('bar', () => {
23
- some_fn();
20
+
21
+ it('accepts this input', () => {
22
+ // ...
24
23
  });
25
- });
26
24
 
27
- // Nested describe scenario
28
- describe('foo', () => {
29
25
  beforeAll(() => {
30
- //some hook code
26
+ createMyDatabase();
31
27
  });
32
- test('bar', () => {
33
- some_fn();
28
+
29
+ it('returns that value', () => {
30
+ // ...
34
31
  });
35
- describe('inner_foo', () => {
32
+
33
+ describe('when the database has specific values', () => {
34
+ const specificValue = '...';
35
+
36
36
  beforeEach(() => {
37
- //some hook code
37
+ seedMyDatabase(specificValue);
38
38
  });
39
- test('inner bar', () => {
40
- some_fn();
39
+
40
+ it('accepts that input', () => {
41
+ // ...
41
42
  });
42
- test('inner bar', () => {
43
- some_fn();
43
+
44
+ it('throws an error', () => {
45
+ // ...
44
46
  });
45
- beforeAll(() => {
46
- //some hook code
47
+
48
+ afterEach(() => {
49
+ clearLogger();
47
50
  });
48
- afterAll(() => {
49
- //some hook code
51
+ beforeEach(() => {
52
+ mockLogger();
50
53
  });
51
- test('inner bar', () => {
52
- some_fn();
54
+
55
+ it('logs a message', () => {
56
+ // ...
53
57
  });
54
58
  });
59
+
60
+ afterAll(() => {
61
+ removeMyDatabase();
62
+ });
55
63
  });
56
64
  ```
57
65
 
@@ -61,35 +69,51 @@ Examples of **correct** code for this rule
61
69
  /* eslint jest/prefer-hooks-on-top: "error" */
62
70
 
63
71
  describe('foo', () => {
64
- beforeEach(() => {
65
- //some hook code
72
+ beforeAll(() => {
73
+ createMyDatabase();
66
74
  });
67
75
 
68
- // Not affected by rule
69
- someSetup();
70
-
71
- afterEach(() => {
72
- //some hook code
76
+ beforeEach(() => {
77
+ seedMyDatabase();
73
78
  });
74
- test('bar', () => {
75
- some_fn();
79
+
80
+ afterAll(() => {
81
+ clearMyDatabase();
76
82
  });
77
- });
78
83
 
79
- // Nested describe scenario
80
- describe('foo', () => {
81
- beforeEach(() => {
82
- //some hook code
84
+ it('accepts this input', () => {
85
+ // ...
83
86
  });
84
- test('bar', () => {
85
- some_fn();
87
+
88
+ it('returns that value', () => {
89
+ // ...
86
90
  });
87
- describe('inner_foo', () => {
91
+
92
+ describe('when the database has specific values', () => {
93
+ const specificValue = '...';
94
+
88
95
  beforeEach(() => {
89
- //some hook code
96
+ seedMyDatabase(specificValue);
90
97
  });
91
- test('inner bar', () => {
92
- some_fn();
98
+
99
+ beforeEach(() => {
100
+ mockLogger();
101
+ });
102
+
103
+ afterEach(() => {
104
+ clearLogger();
105
+ });
106
+
107
+ it('accepts that input', () => {
108
+ // ...
109
+ });
110
+
111
+ it('throws an error', () => {
112
+ // ...
113
+ });
114
+
115
+ it('logs a message', () => {
116
+ // ...
93
117
  });
94
118
  });
95
119
  });
@@ -100,6 +100,8 @@ var _default = (0, _utils.createRule)({
100
100
 
101
101
  return {
102
102
  CallExpression(node) {
103
+ var _matcher$arguments;
104
+
103
105
  if (!(0, _utils.isExpectCall)(node)) {
104
106
  return;
105
107
  }
@@ -112,10 +114,10 @@ var _default = (0, _utils.createRule)({
112
114
  return;
113
115
  }
114
116
 
115
- if (['toMatchInlineSnapshot', 'toThrowErrorMatchingInlineSnapshot'].includes(matcher.name)) {
117
+ if (['toMatchInlineSnapshot', 'toThrowErrorMatchingInlineSnapshot'].includes(matcher.name) && (_matcher$arguments = matcher.arguments) !== null && _matcher$arguments !== void 0 && _matcher$arguments.length) {
116
118
  var _options$inlineMaxSiz;
117
119
 
118
- reportOnViolation(context, matcher.node.parent, { ...options,
120
+ reportOnViolation(context, matcher.arguments[0], { ...options,
119
121
  maxSize: (_options$inlineMaxSiz = options.inlineMaxSize) !== null && _options$inlineMaxSiz !== void 0 ? _options$inlineMaxSiz : options.maxSize
120
122
  });
121
123
  }
@@ -45,18 +45,68 @@ var _default = (0, _utils.createRule)({
45
45
  properties: {
46
46
  onlyFunctionsWithAsyncKeyword: {
47
47
  type: 'boolean'
48
+ },
49
+ onlyFunctionsWithExpectInLoop: {
50
+ type: 'boolean'
48
51
  }
49
52
  },
50
53
  additionalProperties: false
51
54
  }]
52
55
  },
53
56
  defaultOptions: [{
54
- onlyFunctionsWithAsyncKeyword: false
57
+ onlyFunctionsWithAsyncKeyword: false,
58
+ onlyFunctionsWithExpectInLoop: false
55
59
  }],
56
60
 
57
61
  create(context, [options]) {
62
+ let hasExpectInLoop = false;
63
+ let inTestCaseCall = false;
64
+ let inForLoop = false;
65
+
66
+ const shouldCheckFunction = testFunction => {
67
+ if (!options.onlyFunctionsWithAsyncKeyword && !options.onlyFunctionsWithExpectInLoop) {
68
+ return true;
69
+ }
70
+
71
+ if (options.onlyFunctionsWithAsyncKeyword) {
72
+ if (testFunction.async) {
73
+ return true;
74
+ }
75
+ }
76
+
77
+ if (options.onlyFunctionsWithExpectInLoop) {
78
+ if (hasExpectInLoop) {
79
+ return true;
80
+ }
81
+ }
82
+
83
+ return false;
84
+ };
85
+
86
+ const enterForLoop = () => inForLoop = true;
87
+
88
+ const exitForLoop = () => inForLoop = false;
89
+
58
90
  return {
91
+ ForStatement: enterForLoop,
92
+ 'ForStatement:exit': exitForLoop,
93
+ ForInStatement: enterForLoop,
94
+ 'ForInStatement:exit': exitForLoop,
95
+ ForOfStatement: enterForLoop,
96
+ 'ForOfStatement:exit': exitForLoop,
97
+
59
98
  CallExpression(node) {
99
+ if ((0, _utils.isTestCaseCall)(node)) {
100
+ inTestCaseCall = true;
101
+ return;
102
+ }
103
+
104
+ if ((0, _utils.isExpectCall)(node) && inTestCaseCall && inForLoop) {
105
+ hasExpectInLoop = true;
106
+ }
107
+ },
108
+
109
+ 'CallExpression:exit'(node) {
60
110
  if (!(0, _utils.isTestCaseCall)(node)) {
61
111
  return;
62
112
  }
@@ -67,10 +117,15 @@ var _default = (0, _utils.createRule)({
67
117
 
68
118
  const [, testFn] = node.arguments;
69
119
 
70
- if (!(0, _utils.isFunction)(testFn) || testFn.body.type !== _experimentalUtils.AST_NODE_TYPES.BlockStatement || options.onlyFunctionsWithAsyncKeyword && !testFn.async) {
120
+ if (!(0, _utils.isFunction)(testFn) || testFn.body.type !== _experimentalUtils.AST_NODE_TYPES.BlockStatement) {
121
+ return;
122
+ }
123
+
124
+ if (!shouldCheckFunction(testFn)) {
71
125
  return;
72
126
  }
73
127
 
128
+ hasExpectInLoop = false;
74
129
  const testFuncBody = testFn.body.body;
75
130
 
76
131
  if (!isFirstLineExprStmt(testFuncBody)) {
@@ -16,7 +16,7 @@ var _default = (0, _utils.createRule)({
16
16
  recommended: false
17
17
  },
18
18
  messages: {
19
- noHookOnTop: 'Move all hooks before test cases'
19
+ noHookOnTop: 'Hooks should come before test cases'
20
20
  },
21
21
  schema: [],
22
22
  type: 'suggestion'
@@ -29,11 +29,11 @@ const populateIgnores = ignore => {
29
29
  }
30
30
 
31
31
  if (ignore.includes(_utils.TestCaseName.test)) {
32
- ignores.push(...Object.keys(_utils.TestCaseName));
32
+ ignores.push(...Object.keys(_utils.TestCaseName).filter(k => k.endsWith(_utils.TestCaseName.test)));
33
33
  }
34
34
 
35
35
  if (ignore.includes(_utils.TestCaseName.it)) {
36
- ignores.push(...Object.keys(_utils.TestCaseName));
36
+ ignores.push(...Object.keys(_utils.TestCaseName).filter(k => k.endsWith(_utils.TestCaseName.it)));
37
37
  }
38
38
 
39
39
  return ignores;
@@ -32,52 +32,8 @@ const isBooleanEqualityMatcher = matcher => (0, _utils.isParsedEqualityMatcherCa
32
32
  * @param {CallExpression} node
33
33
  *
34
34
  * @return {node is FixableIncludesCallExpression}
35
- *
36
- * @todo support `['includes']()` syntax (remove last property.type check to begin)
37
- * @todo break out into `isMethodCall<Name extends string>(node: TSESTree.Node, method: Name)` util-fn
38
- */
39
- const isFixableIncludesCallExpression = node => node.type === _experimentalUtils.AST_NODE_TYPES.CallExpression && node.callee.type === _experimentalUtils.AST_NODE_TYPES.MemberExpression && (0, _utils.isSupportedAccessor)(node.callee.property, 'includes') && node.callee.property.type === _experimentalUtils.AST_NODE_TYPES.Identifier && (0, _utils.hasOnlyOneArgument)(node);
40
-
41
- const buildToContainFuncExpectation = negated => negated ? `${_utils.ModifierName.not}.toContain` : 'toContain';
42
- /**
43
- * Finds the first `.` character token between the `object` & `property` of the given `member` expression.
44
- *
45
- * @param {TSESTree.MemberExpression} member
46
- * @param {SourceCode} sourceCode
47
- *
48
- * @return {Token | null}
49
35
  */
50
-
51
-
52
- const findPropertyDotToken = (member, sourceCode) => sourceCode.getFirstTokenBetween(member.object, member.property, token => token.value === '.');
53
-
54
- const getNegationFixes = (node, modifier, matcher, sourceCode, fixer, fileName) => {
55
- const [containArg] = node.arguments;
56
- const negationPropertyDot = findPropertyDotToken(modifier.node, sourceCode);
57
- const toContainFunc = buildToContainFuncExpectation((0, _utils.followTypeAssertionChain)(matcher.arguments[0]).value);
58
- /* istanbul ignore if */
59
-
60
- if (negationPropertyDot === null) {
61
- throw new Error(`Unexpected null when attempting to fix ${fileName} - please file a github issue at https://github.com/jest-community/eslint-plugin-jest`);
62
- }
63
-
64
- return [fixer.remove(negationPropertyDot), fixer.remove(modifier.node.property), fixer.replaceText(matcher.node.property, toContainFunc), fixer.replaceText(matcher.arguments[0], sourceCode.getText(containArg))];
65
- };
66
-
67
- const getCommonFixes = (node, sourceCode, fileName) => {
68
- const [containArg] = node.arguments;
69
- const includesCallee = node.callee;
70
- const propertyDot = findPropertyDotToken(includesCallee, sourceCode);
71
- const closingParenthesis = sourceCode.getTokenAfter(containArg);
72
- const openParenthesis = sourceCode.getTokenBefore(containArg);
73
- /* istanbul ignore if */
74
-
75
- if (propertyDot === null || closingParenthesis === null || openParenthesis === null) {
76
- throw new Error(`Unexpected null when attempting to fix ${fileName} - please file a github issue at https://github.com/jest-community/eslint-plugin-jest`);
77
- }
78
-
79
- return [containArg, includesCallee.property, propertyDot, closingParenthesis, openParenthesis];
80
- }; // expect(array.includes(<value>)[not.]{toBe,toEqual}(<boolean>)
36
+ const isFixableIncludesCallExpression = node => node.type === _experimentalUtils.AST_NODE_TYPES.CallExpression && node.callee.type === _experimentalUtils.AST_NODE_TYPES.MemberExpression && (0, _utils.isSupportedAccessor)(node.callee.property, 'includes') && (0, _utils.hasOnlyOneArgument)(node); // expect(array.includes(<value>)[not.]{toBe,toEqual}(<boolean>)
81
37
 
82
38
 
83
39
  var _default = (0, _utils.createRule)({
@@ -106,7 +62,8 @@ var _default = (0, _utils.createRule)({
106
62
 
107
63
  const {
108
64
  expect: {
109
- arguments: [includesCall]
65
+ arguments: [includesCall],
66
+ range: [, expectCallEnd]
110
67
  },
111
68
  matcher,
112
69
  modifier
@@ -118,19 +75,14 @@ var _default = (0, _utils.createRule)({
118
75
 
119
76
  context.report({
120
77
  fix(fixer) {
121
- const sourceCode = context.getSourceCode();
122
- const fileName = context.getFilename();
123
- const fixArr = getCommonFixes(includesCall, sourceCode, fileName).map(target => fixer.remove(target));
124
-
125
- if (modifier) {
126
- return getNegationFixes(includesCall, modifier, matcher, sourceCode, fixer, fileName).concat(fixArr);
127
- }
128
-
129
- const toContainFunc = buildToContainFuncExpectation(!(0, _utils.followTypeAssertionChain)(matcher.arguments[0]).value);
130
- const [containArg] = includesCall.arguments;
131
- fixArr.push(fixer.replaceText(matcher.node.property, toContainFunc));
132
- fixArr.push(fixer.replaceText(matcher.arguments[0], sourceCode.getText(containArg)));
133
- return fixArr;
78
+ const sourceCode = context.getSourceCode(); // we need to negate the expectation if the current expected
79
+ // value is itself negated by the "not" modifier
80
+
81
+ const addNotModifier = (0, _utils.followTypeAssertionChain)(matcher.arguments[0]).value === !!modifier;
82
+ return [// remove the "includes" call entirely
83
+ fixer.removeRange([includesCall.callee.property.range[0] - 1, includesCall.range[1]]), // replace the current matcher with "toContain", adding "not" if needed
84
+ fixer.replaceTextRange([expectCallEnd, matcher.node.range[1]], addNotModifier ? `.${_utils.ModifierName.not}.toContain` : '.toContain'), // replace the matcher argument with the value from the "includes"
85
+ fixer.replaceText(matcher.arguments[0], sourceCode.getText(includesCall.arguments[0]))];
134
86
  },
135
87
 
136
88
  messageId: 'useToContain',
@@ -40,20 +40,15 @@ var _default = (0, _utils.createRule)({
40
40
  matcher
41
41
  } = (0, _utils.parseExpectCall)(node);
42
42
 
43
- if (!matcher || !(0, _utils.isParsedEqualityMatcherCall)(matcher) || (argument === null || argument === void 0 ? void 0 : argument.type) !== _experimentalUtils.AST_NODE_TYPES.MemberExpression || !(0, _utils.isSupportedAccessor)(argument.property, 'length') || argument.property.type !== _experimentalUtils.AST_NODE_TYPES.Identifier) {
43
+ if (!matcher || !(0, _utils.isParsedEqualityMatcherCall)(matcher) || (argument === null || argument === void 0 ? void 0 : argument.type) !== _experimentalUtils.AST_NODE_TYPES.MemberExpression || !(0, _utils.isSupportedAccessor)(argument.property, 'length')) {
44
44
  return;
45
45
  }
46
46
 
47
47
  context.report({
48
48
  fix(fixer) {
49
- const propertyDot = context.getSourceCode().getFirstTokenBetween(argument.object, argument.property, token => token.value === '.');
50
- /* istanbul ignore if */
51
-
52
- if (propertyDot === null) {
53
- throw new Error(`Unexpected null when attempting to fix ${context.getFilename()} - please file a github issue at https://github.com/jest-community/eslint-plugin-jest`);
54
- }
55
-
56
- return [fixer.remove(propertyDot), fixer.remove(argument.property), fixer.replaceText(matcher.node.property, 'toHaveLength')];
49
+ return [// remove the "length" property accessor
50
+ fixer.removeRange([argument.property.range[0] - 1, argument.range[1]]), // replace the current matcher with "toHaveLength"
51
+ fixer.replaceTextRange([matcher.node.object.range[1], matcher.node.range[1]], '.toHaveLength')];
57
52
  },
58
53
 
59
54
  messageId: 'useToHaveLength',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-jest",
3
- "version": "25.3.1",
3
+ "version": "25.4.0",
4
4
  "description": "Eslint rules for Jest",
5
5
  "keywords": [
6
6
  "eslint",
@@ -89,8 +89,8 @@
89
89
  "@babel/core": "^7.4.4",
90
90
  "@babel/preset-env": "^7.4.4",
91
91
  "@babel/preset-typescript": "^7.3.3",
92
- "@commitlint/cli": "^15.0.0",
93
- "@commitlint/config-conventional": "^15.0.0",
92
+ "@commitlint/cli": "^16.0.0",
93
+ "@commitlint/config-conventional": "^16.0.0",
94
94
  "@schemastore/package": "^0.0.6",
95
95
  "@semantic-release/changelog": "^6.0.0",
96
96
  "@semantic-release/git": "^10.0.0",
@@ -111,6 +111,8 @@
111
111
  "eslint-plugin-import": "^2.25.1",
112
112
  "eslint-plugin-node": "^11.0.0",
113
113
  "eslint-plugin-prettier": "^3.4.1",
114
+ "eslint-remote-tester": "^2.1.0",
115
+ "eslint-remote-tester-repositories": "^0.0.3",
114
116
  "husky": "^7.0.2",
115
117
  "is-ci": "^3.0.0",
116
118
  "jest": "^27.0.0",