chore: update `eslint-plugin-unicorn` (#15336)

This commit is contained in:
Simen Bekkhus 2024-10-04 10:13:27 +02:00 committed by GitHub
parent b0eb836868
commit 0a0a9f7375
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
24 changed files with 799 additions and 815 deletions

View File

@ -226,6 +226,7 @@ module.exports = {
'unicorn/no-static-only-class': 'off', 'unicorn/no-static-only-class': 'off',
'unicorn/prefer-number-properties': 'off', 'unicorn/prefer-number-properties': 'off',
'unicorn/prefer-string-raw': 'off', 'unicorn/prefer-string-raw': 'off',
'unicorn/prefer-global-this': 'off',
}, },
}, },
// demonstration of matchers usage // demonstration of matchers usage

View File

@ -13,15 +13,15 @@ exports[`Wrong globals for environment on node <=18 print useful error for navig
ReferenceError: navigator is not defined ReferenceError: navigator is not defined
30 | 31 |
31 | test('use navigator', () => { 32 | test('use navigator', () => {
> 32 | const userAgent = navigator.userAgent; > 33 | const userAgent = navigator.userAgent;
| ^ | ^
33 | 34 |
34 | console.log(userAgent); 35 | console.log(userAgent);
35 | 36 |
at Object.navigator (__tests__/node.js:32:21)" at Object.navigator (__tests__/node.js:33:21)"
`; `;
exports[`Wrong globals for environment print useful error for document 1`] = ` exports[`Wrong globals for environment print useful error for document 1`] = `
@ -83,15 +83,15 @@ exports[`Wrong globals for environment print useful error for window 1`] = `
ReferenceError: window is not defined ReferenceError: window is not defined
22 |
23 | test('use window', () => { 23 | test('use window', () => {
> 24 | const location = window.location; 24 | // eslint-disable-next-line unicorn/prefer-global-this
> 25 | const location = window.location;
| ^ | ^
25 | 26 |
26 | console.log(location); 27 | console.log(location);
27 | 28 |
at Object.window (__tests__/node.js:24:20)" at Object.window (__tests__/node.js:25:20)"
`; `;
exports[`Wrong globals for environment print useful error when it explodes during evaluation 1`] = ` exports[`Wrong globals for environment print useful error when it explodes during evaluation 1`] = `

View File

@ -30,11 +30,11 @@ test('can mock console.error calls from jsdom', () => {
function onError(event) {} function onError(event) {}
window.addEventListener('error', onError); globalThis.addEventListener('error', onError);
fakeNode.addEventListener(evtType, callCallback, false); fakeNode.addEventListener(evtType, callCallback, false);
evt.initEvent(evtType, false, false); evt.initEvent(evtType, false, false);
fakeNode.dispatchEvent(evt); fakeNode.dispatchEvent(evt);
window.removeEventListener('error', onError); globalThis.removeEventListener('error', onError);
expect(console.error).toHaveBeenCalledTimes(1); expect(console.error).toHaveBeenCalledTimes(1);
expect(console.error).toHaveBeenCalledWith( expect(console.error).toHaveBeenCalledWith(

View File

@ -8,6 +8,7 @@
const {isArrayBuffer} = require('util').types; const {isArrayBuffer} = require('util').types;
const isJSDOM = const isJSDOM =
// eslint-disable-next-line unicorn/prefer-global-this
typeof window !== 'undefined' && typeof document !== 'undefined'; typeof window !== 'undefined' && typeof document !== 'undefined';
const skipTestJSDOM = isJSDOM ? test.skip : test; const skipTestJSDOM = isJSDOM ? test.skip : test;

View File

@ -8,5 +8,5 @@
/*eslint-env browser */ /*eslint-env browser */
test('found url jestjs.io', () => { test('found url jestjs.io', () => {
expect(window.location.href).toBe('https://jestjs.io/'); expect(globalThis.location.href).toBe('https://jestjs.io/');
}); });

View File

@ -10,16 +10,16 @@
'use strict'; 'use strict';
const mockPerformanceMark = jest.fn(); const mockPerformanceMark = jest.fn();
window.performance.mark = mockPerformanceMark; globalThis.performance.mark = mockPerformanceMark;
test('fakes all APIs', () => { test('fakes all APIs', () => {
jest.useFakeTimers(); jest.useFakeTimers();
expect(window.performance.mark).toBeUndefined(); expect(globalThis.performance.mark).toBeUndefined();
}); });
test('does not fake `performance` instance', () => { test('does not fake `performance` instance', () => {
jest.useFakeTimers({doNotFake: ['performance']}); jest.useFakeTimers({doNotFake: ['performance']});
expect(window.performance.mark).toBe(mockPerformanceMark); expect(globalThis.performance.mark).toBe(mockPerformanceMark);
}); });

View File

@ -17,7 +17,7 @@ it('can assert on errors across nested event loops', () => {
throw new Error('This should be caught.'); throw new Error('This should be caught.');
}); });
let caught = null; let caught = null;
window.addEventListener('error', e => { globalThis.addEventListener('error', e => {
caught = e.error; caught = e.error;
}); });
expect(() => { expect(() => {

View File

@ -29,10 +29,8 @@ describe('parent', () => {
}); });
it('can override atob and btoa', () => { it('can override atob and btoa', () => {
// eslint-disable-next-line no-restricted-globals globalThis.atob = () => 'hello';
global.atob = () => 'hello'; globalThis.btoa = () => 'there';
// eslint-disable-next-line no-restricted-globals
global.btoa = () => 'there';
expect(`${atob()} ${btoa()}`).toBe('hello there'); expect(`${atob()} ${btoa()}`).toBe('hello there');
}); });

View File

@ -11,5 +11,5 @@
/*eslint-env browser */ /*eslint-env browser */
test('use jsdom and set the URL in this test file', () => { test('use jsdom and set the URL in this test file', () => {
expect(window.location.href).toBe('https://jestjs.io/'); expect(globalThis.location.href).toBe('https://jestjs.io/');
}); });

View File

@ -21,6 +21,7 @@ test('use document', () => {
}); });
test('use window', () => { test('use window', () => {
// eslint-disable-next-line unicorn/prefer-global-this
const location = window.location; const location = window.location;
console.log(location); console.log(location);

View File

@ -41,7 +41,7 @@
"eslint-plugin-markdown": "^3.0.0", "eslint-plugin-markdown": "^3.0.0",
"eslint-plugin-prettier": "^5.0.0", "eslint-plugin-prettier": "^5.0.0",
"eslint-plugin-promise": "^6.1.1", "eslint-plugin-promise": "^6.1.1",
"eslint-plugin-unicorn": "^55.0.0", "eslint-plugin-unicorn": "^56.0.0",
"execa": "^5.0.0", "execa": "^5.0.0",
"find-process": "^1.4.1", "find-process": "^1.4.1",
"glob": "^10.3.10", "glob": "^10.3.10",

View File

@ -164,7 +164,7 @@ const extendPathsF = (
); );
// Optimization: skip diagonals in which paths cannot ever overlap. // Optimization: skip diagonals in which paths cannot ever overlap.
const nF = d < iMaxF ? d : iMaxF; const nF = Math.min(d, iMaxF);
// The diagonals kF are odd when d is odd and even when d is even. // The diagonals kF are odd when d is odd and even when d is even.
for (iF += 1, kF += 2; iF <= nF; iF += 1, kF += 2) { for (iF += 1, kF += 2; iF <= nF; iF += 1, kF += 2) {
@ -217,7 +217,7 @@ const extendPathsR = (
); );
// Optimization: skip diagonals in which paths cannot ever overlap. // Optimization: skip diagonals in which paths cannot ever overlap.
const nR = d < iMaxR ? d : iMaxR; const nR = Math.min(d, iMaxR);
// The diagonals kR are odd when d is odd and even when d is even. // The diagonals kR are odd when d is odd and even when d is even.
for (iR += 1, kR -= 2; iR <= nR; iR += 1, kR -= 2) { for (iR += 1, kR -= 2; iR <= nR; iR += 1, kR -= 2) {
@ -278,7 +278,7 @@ const extendOverlappablePathsF = (
let aIndexPrev1 = NOT_YET_SET; // prev value of [iF - 1] in next iteration let aIndexPrev1 = NOT_YET_SET; // prev value of [iF - 1] in next iteration
// Optimization: skip diagonals in which paths cannot ever overlap. // Optimization: skip diagonals in which paths cannot ever overlap.
const nF = d < iMaxF ? d : iMaxF; const nF = Math.min(d, iMaxF);
// The diagonals kF = 2 * iF - d are odd when d is odd and even when d is even. // The diagonals kF = 2 * iF - d are odd when d is odd and even when d is even.
for (let iF = 0, kF = -d; iF <= nF; iF += 1, kF += 2) { for (let iF = 0, kF = -d; iF <= nF; iF += 1, kF += 2) {
@ -411,7 +411,7 @@ const extendOverlappablePathsR = (
let aIndexPrev1 = NOT_YET_SET; // prev value of [iR - 1] in next iteration let aIndexPrev1 = NOT_YET_SET; // prev value of [iR - 1] in next iteration
// Optimization: skip diagonals in which paths cannot ever overlap. // Optimization: skip diagonals in which paths cannot ever overlap.
const nR = d < iMaxR ? d : iMaxR; const nR = Math.min(d, iMaxR);
// The diagonals kR = d - 2 * iR are odd when d is odd and even when d is even. // The diagonals kR = d - 2 * iR are odd when d is odd and even when d is even.
for (let iR = 0, kR = d; iR <= nR; iR += 1, kR -= 2) { for (let iR = 0, kR = d; iR <= nR; iR += 1, kR -= 2) {

View File

@ -216,8 +216,8 @@ const eventHandler: Circus.EventHandler = (event, state) => {
} }
case 'test_retry': { case 'test_retry': {
const logErrorsBeforeRetry: boolean = const logErrorsBeforeRetry: boolean =
// eslint-disable-next-line no-restricted-globals ((globalThis as Global.Global)[LOG_ERRORS_BEFORE_RETRY] as any) ||
((global as Global.Global)[LOG_ERRORS_BEFORE_RETRY] as any) || false; false;
if (logErrorsBeforeRetry) { if (logErrorsBeforeRetry) {
event.test.retryReasons.push(...event.test.errors); event.test.retryReasons.push(...event.test.errors);
} }
@ -226,13 +226,12 @@ const eventHandler: Circus.EventHandler = (event, state) => {
} }
case 'run_start': { case 'run_start': {
state.hasStarted = true; state.hasStarted = true;
/* eslint-disable no-restricted-globals */ if ((globalThis as Global.Global)[TEST_TIMEOUT_SYMBOL]) {
if ((global as Global.Global)[TEST_TIMEOUT_SYMBOL]) { state.testTimeout = (globalThis as Global.Global)[
state.testTimeout = (global as Global.Global)[
TEST_TIMEOUT_SYMBOL TEST_TIMEOUT_SYMBOL
] as number; ] as number;
} }
/* eslint-enable */
break; break;
} }
case 'run_finish': { case 'run_finish': {

View File

@ -69,19 +69,17 @@ const _runTestsForDescribeBlock = async (
// Tests that fail and are retried we run after other tests // Tests that fail and are retried we run after other tests
const retryTimes = const retryTimes =
// eslint-disable-next-line no-restricted-globals Number.parseInt((globalThis as Global.Global)[RETRY_TIMES] as string, 10) ||
Number.parseInt((global as Global.Global)[RETRY_TIMES] as string, 10) || 0; 0;
const waitBeforeRetry = const waitBeforeRetry =
Number.parseInt( Number.parseInt(
// eslint-disable-next-line no-restricted-globals (globalThis as Global.Global)[WAIT_BEFORE_RETRY] as string,
(global as Global.Global)[WAIT_BEFORE_RETRY] as string,
10, 10,
) || 0; ) || 0;
const retryImmediately: boolean = const retryImmediately: boolean =
// eslint-disable-next-line no-restricted-globals ((globalThis as Global.Global)[RETRY_IMMEDIATELY] as any) || false;
((global as Global.Global)[RETRY_IMMEDIATELY] as any) || false;
const deferredRetryTests = []; const deferredRetryTests = [];

View File

@ -38,18 +38,16 @@ const createState = (): Circus.State => {
}; };
}; };
/* eslint-disable no-restricted-globals */
export const resetState = (): void => { export const resetState = (): void => {
(global as Global.Global)[STATE_SYM] = createState(); (globalThis as Global.Global)[STATE_SYM] = createState();
}; };
resetState(); resetState();
export const getState = (): Circus.State => export const getState = (): Circus.State =>
(global as Global.Global)[STATE_SYM] as Circus.State; (globalThis as Global.Global)[STATE_SYM] as Circus.State;
export const setState = (state: Circus.State): Circus.State => export const setState = (state: Circus.State): Circus.State =>
((global as Global.Global)[STATE_SYM] = state); ((globalThis as Global.Global)[STATE_SYM] = state);
/* eslint-enable */
export const dispatch = async (event: Circus.AsyncEvent): Promise<void> => { export const dispatch = async (event: Circus.AsyncEvent): Promise<void> => {
for (const handler of eventHandlers) { for (const handler of eventHandlers) {

View File

@ -60,15 +60,13 @@ export const create = function (createOptions: Record<string, any>): Jasmine {
enumerable: true, enumerable: true,
get() { get() {
return ( return (
// eslint-disable-next-line no-restricted-globals (globalThis as Global.Global)[testTimeoutSymbol] ||
(global as Global.Global)[testTimeoutSymbol] ||
createOptions.testTimeout || createOptions.testTimeout ||
5000 5000
); );
}, },
set(value) { set(value) {
// eslint-disable-next-line no-restricted-globals (globalThis as Global.Global)[testTimeoutSymbol] = value;
(global as Global.Global)[testTimeoutSymbol] = value;
}, },
}); });

View File

@ -12,12 +12,10 @@ import type {Global} from '@jest/types';
import type {JasmineMatchersObject} from './types'; import type {JasmineMatchersObject} from './types';
export default function jestExpectAdapter(config: {expand: boolean}): void { export default function jestExpectAdapter(config: {expand: boolean}): void {
// eslint-disable-next-line no-restricted-globals (globalThis as Global.Global).expect = jestExpect;
(global as Global.Global).expect = jestExpect;
jestExpect.setState({expand: config.expand}); jestExpect.setState({expand: config.expand});
// eslint-disable-next-line no-restricted-globals const jasmine = (globalThis as Global.Global).jasmine;
const jasmine = (global as Global.Global).jasmine;
jasmine.anything = jestExpect.anything; jasmine.anything = jestExpect.anything;
jasmine.any = jestExpect.any; jasmine.any = jestExpect.any;
jasmine.objectContaining = jestExpect.objectContaining; jasmine.objectContaining = jestExpect.objectContaining;

View File

@ -504,7 +504,7 @@ type PrintLabel = (string: string) => string;
export const getLabelPrinter = (...strings: Array<string>): PrintLabel => { export const getLabelPrinter = (...strings: Array<string>): PrintLabel => {
const maxLength = strings.reduce( const maxLength = strings.reduce(
(max, string) => (string.length > max ? string.length : max), (max, string) => Math.max(string.length, max),
0, 0,
); );
return (string: string): string => return (string: string): string =>

View File

@ -12,11 +12,11 @@
/* eslint-env browser*/ /* eslint-env browser*/
function exampleDispatch() { function exampleDispatch() {
window.dispatchEvent(new CustomEvent('event', {})); globalThis.dispatchEvent(new CustomEvent('event', {}));
} }
describe('spy on `dispatchEvent`', () => { describe('spy on `dispatchEvent`', () => {
const dispatchEventSpy = jest.spyOn(window, 'dispatchEvent'); const dispatchEventSpy = jest.spyOn(globalThis, 'dispatchEvent');
it('should be called', () => { it('should be called', () => {
exampleDispatch(); exampleDispatch();

View File

@ -81,7 +81,7 @@ function findGlobalPaths(): Array<string> {
if (resolvePaths) { if (resolvePaths) {
// the global paths start one after the root node_modules // the global paths start one after the root node_modules
const rootIndex = resolvePaths.indexOf(globalPath); const rootIndex = resolvePaths.indexOf(globalPath);
return rootIndex > -1 ? resolvePaths.slice(rootIndex + 1) : []; return rootIndex === -1 ? [] : resolvePaths.slice(rootIndex + 1);
} }
return []; return [];
} }

View File

@ -411,10 +411,10 @@ const traverseAst = (
[], [],
); );
if (snapshotIndex > -1) { if (snapshotIndex === -1) {
args[snapshotIndex] = replacementNode;
} else {
args.push(replacementNode); args.push(replacementNode);
} else {
args[snapshotIndex] = replacementNode;
} }
}); });

View File

@ -21,7 +21,7 @@ setPrettyPrint([DOMElement]);
describe('pretty-format', () => { describe('pretty-format', () => {
// Test is not related to plugin but is related to jsdom testing environment. // Test is not related to plugin but is related to jsdom testing environment.
it('prints global window as constructor name alone', () => { it('prints global window as constructor name alone', () => {
expect(prettyFormat(window)).toBe('[Window]'); expect(prettyFormat(globalThis)).toBe('[Window]');
}); });
}); });

View File

@ -63,6 +63,7 @@ const getConstructorName = (val: new (...args: Array<any>) => unknown) =>
/* global window */ /* global window */
/** Is val is equal to global window object? Works even if it does not exist :) */ /** Is val is equal to global window object? Works even if it does not exist :) */
const isWindow = (val: unknown) => const isWindow = (val: unknown) =>
// eslint-disable-next-line unicorn/prefer-global-this
typeof window !== 'undefined' && val === window; typeof window !== 'undefined' && val === window;
const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/;

1495
yarn.lock

File diff suppressed because it is too large Load Diff