Skip to content

Commit

Permalink
Adding new EsLint rules (#9445)
Browse files Browse the repository at this point in the history
* enforce dot notation

* enforce eqeqeq

* fix unit tests

* enforce const

* enforce consistent-type-imports

* enable no-var rule (#9446)

Co-authored-by: SCG82 <scg082+github@gmail.com>
  • Loading branch information
christian-bromann and SCG82 committed Dec 24, 2022
1 parent 23667d5 commit 62e24d4
Show file tree
Hide file tree
Showing 155 changed files with 436 additions and 353 deletions.
14 changes: 12 additions & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,26 @@ module.exports = {
sourceType: 'module'
},
rules: {
quotes: ['error', 'single', { avoidEscape: true }],
camelcase: ['error', { properties: 'never' }],
semi: ['error', 'never'],
indent: [2, 4],
eqeqeq: ['error', 'always'],

'prefer-const': 'error',
'no-multiple-empty-lines': [2, { 'max': 1, 'maxEOF': 1 }],
'array-bracket-spacing': ['error', 'never'],
'brace-style': ['error', '1tbs', { allowSingleLine: true }],
camelcase: ['error', { properties: 'never' }],
'comma-spacing': ['error', { before: false, after: true }],
'no-lonely-if': 'error',
'dot-notation': 'error',
'no-else-return': 'error',
'no-tabs': 'error',
'no-trailing-spaces': ['error', {
skipBlankLines: false,
ignoreComments: false
}],
quotes: ['error', 'single', { avoidEscape: true }],
'no-var': 'error',
'unicode-bom': ['error', 'never'],
'object-curly-spacing': ['error', 'always'],
'keyword-spacing':['error'],
Expand All @@ -44,9 +48,15 @@ module.exports = {
// see https://stackoverflow.com/questions/55280555/typescript-eslint-eslint-plugin-error-route-is-defined-but-never-used-no-un
'no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'error',
'@typescript-eslint/consistent-type-imports': 'error',
'no-undef': 'off',
// allow overloads
'no-redeclare': 'off'
}
}, {
files: ['*.test.ts'],
rules: {
'dot-notation': 'off'
}
}]
}
12 changes: 6 additions & 6 deletions examples/appium/helpers/drawHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function circleAction (h, k) {

actions.push(prev)
for (; theta < 2*Math.PI; theta+=2*Math.PI/36) {
var next = { x: h + r * Math.cos(theta), y: k + r * Math.sin(theta) }
const next = { x: h + r * Math.cos(theta), y: k + r * Math.sin(theta) }
actions.push({ action: 'moveTo', x: next.x - prev.x, y: next.y - prev.y })
prev = next
}
Expand All @@ -37,7 +37,7 @@ export function arcAction(start, end) {
actions.push(prev)

for (; theta < end; theta += 2 * Math.PI / 100) {
var next = { x: h + r * Math.cos(theta), y: k + r * Math.sin(theta) }
const next = { x: h + r * Math.cos(theta), y: k + r * Math.sin(theta) }
actions.push({ action: 'moveTo', x: next.x - prev.x, y: next.y - prev.y })
prev = next
}
Expand All @@ -56,13 +56,13 @@ export function innerArcAction(start, end) {
let theta = start
const step = 4 * Math.PI / 100

var prev = { action: 'press', x: h - r * Math.cos(theta), y: k + r * Math.sin(theta) }
var actions = []
let prev = { action: 'press', x: h - r * Math.cos(theta), y: k + r * Math.sin(theta) }
const actions = []
actions.push(prev)

for (; theta < end; theta += step) {
var rad = 7.5991 * Math.pow(theta - start - Math.PI, 2) + 25
var next = { x: h - rad * Math.cos(theta), y: k + rad * Math.sin(theta) }
const rad = 7.5991 * Math.pow(theta - start - Math.PI, 2) + 25
const next = { x: h - rad * Math.cos(theta), y: k + rad * Math.sin(theta) }
actions.push({ action: 'moveTo', x: next.x - prev.x, y: next.y - prev.y })
prev = next
}
Expand Down
2 changes: 1 addition & 1 deletion examples/multiremote/webrtc.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const { multiremote } = require('../../packages/webdriverio/build/index.js')
}
})

var channel = Math.round(Math.random() * 10e10)
const channel = Math.round(Math.random() * 10e10)

await matrix.url('https://apprtc.appspot.com/r/' + channel)

Expand Down
2 changes: 1 addition & 1 deletion examples/wdio/cucumber/step-definitions.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ When(/^I add the following groceries$/, async (table) => {
})

Then(/^should the element "([^"]*)" be (\d+)px wide and (\d+)px high$/, async (selector, width, height) => {
var elemSize = await $(selector).getSize()
const elemSize = await $(selector).getSize()
expect(elemSize.width).toBe(width)
expect(elemSize.height).toBe(height)
})
Expand Down
2 changes: 1 addition & 1 deletion packages/devtools/src/commands/addCookie.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Cookie } from '@wdio/protocols'
import type { Cookie } from '@wdio/protocols'

import type DevToolsDriver from '../devtoolsdriver'

Expand Down
6 changes: 4 additions & 2 deletions packages/devtools/src/commands/performActions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { _keyDefinitions, KeyInput } from 'puppeteer-core/lib/cjs/puppeteer/common/USKeyboardLayout.js'
import type { KeyInput } from 'puppeteer-core/lib/cjs/puppeteer/common/USKeyboardLayout.js'
import { _keyDefinitions } from 'puppeteer-core/lib/cjs/puppeteer/common/USKeyboardLayout.js'
import type { Keyboard, Mouse } from 'puppeteer-core/lib/cjs/puppeteer/common/Input.js'

import getElementRect from './getElementRect.js'
Expand Down Expand Up @@ -133,8 +134,9 @@ export default async function performActions(

const cmd = singleAction.type.slice(POINTER.length).toLowerCase()
const keyboardFn = (page.mouse[cmd as keyof Mouse] as Function).bind(page.mouse)
let { x, y, duration, button, origin } = singleAction
const { duration, button, origin } = singleAction

let { x, y } = singleAction
if (cmd === 'move') {
/**
* set location relative from last position if origin is set to pointer
Expand Down
2 changes: 1 addition & 1 deletion packages/devtools/src/commands/switchToFrame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export default async function switchToFrame (
/**
* `page` has `frames` method while `frame` has `childFrames` method
*/
let getFrames = (page as unknown as Page).frames || page.childFrames
const getFrames = (page as unknown as Page).frames || page.childFrames
const childFrames = await getFrames.apply(page)
const childFrame = childFrames[id]

Expand Down
6 changes: 3 additions & 3 deletions packages/devtools/src/devtoolsdriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import * as commands from './commands/index.js'
import ElementStore from './elementstore.js'
import { validate, sanitizeError } from './utils.js'
import { DEFAULT_IMPLICIT_TIMEOUT, DEFAULT_PAGELOAD_TIMEOUT, DEFAULT_SCRIPT_TIMEOUT } from './constants.js'
import { ActiveListener } from './types.js'
import type { ActiveListener } from './types.js'

const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
const log = logger('devtools')
Expand Down Expand Up @@ -46,7 +46,7 @@ export default class DevToolsDriver {
)
)

for (let filename of files) {
for (const filename of files) {
const commandName = path.basename(filename, path.extname(filename))

if (!commandName) {
Expand Down Expand Up @@ -288,7 +288,7 @@ export default class DevToolsDriver {
}

const pageloadTimeout = this.timeouts.get('pageLoad')
const pageloadTimeoutReached = pageloadTimeout != null
const pageloadTimeoutReached = typeof pageloadTimeout !== 'undefined'
? Date.now() - pendingNavigationStart > pageloadTimeout
: false

Expand Down
2 changes: 1 addition & 1 deletion packages/devtools/src/elementstore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default class ElementStore {
set (elementHandle: ElementHandle) {
const index = `ELEMENT-${++this._index}`
this._elementMap.set(index, elementHandle)
const frame = elementHandle.executionContext()['_world']?.frame()
const frame = elementHandle.executionContext()._world?.frame()
if (frame) {
let elementIndexes = this._frameMap.get(frame)
if (!elementIndexes) {
Expand Down
2 changes: 1 addition & 1 deletion packages/devtools/src/finder/edge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ function findEdgeExecutables(folder: string) {
const argumentsRegex = /(^[^ ]+).*/ // Take everything up to the first space
const edgeExecRegex = '^Exec=/.*/(edge)-.*'

let installations: string[] = []
const installations: string[] = []
if (canAccess(folder)) {
let execPaths

Expand Down
2 changes: 1 addition & 1 deletion packages/devtools/src/finder/firefox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ function findFirefoxExecutables(folder: string) {
const argumentsRegex = /(^[^ ]+).*/ // Take everything up to the first space
const edgeExecRegex = '^Exec=/.*/(firefox)-.*'

let installations: string[] = []
const installations: string[] = []
if (canAccess(folder)) {
let execPaths

Expand Down
2 changes: 1 addition & 1 deletion packages/devtools/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export default class DevTools {
): Promise<Client> {
const params = validateConfig(DEFAULTS, options)

if (params.logLevel && (!options.logLevels || !(options.logLevels as any)['devtools'])) {
if (params.logLevel && (!options.logLevels || !(options.logLevels as any).devtools)) {
logger.setLevel('devtools', params.logLevel)
}

Expand Down
14 changes: 8 additions & 6 deletions packages/devtools/src/launcher.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { launch as launchChromeBrowser, Options } from 'chrome-launcher'
import puppeteer, { PuppeteerLaunchOptions, KnownDevices, Puppeteer, ConnectOptions } from 'puppeteer-core'
import type { Options } from 'chrome-launcher'
import { launch as launchChromeBrowser } from 'chrome-launcher'
import type { PuppeteerLaunchOptions, ConnectOptions } from 'puppeteer-core'
import puppeteer, { KnownDevices, Puppeteer } from 'puppeteer-core'
import logger from '@wdio/logger'
import type { Browser } from 'puppeteer-core/lib/cjs/puppeteer/api/Browser'
import type { Capabilities } from '@wdio/types'
Expand Down Expand Up @@ -44,8 +46,8 @@ async function launchChrome (capabilities: ExtendedCapabilities) {
* This should be cleaned up for v7 release
* ToDo(Christian): v7 cleanup
*/
let ignoreDefaultArgs = (capabilities as any).ignoreDefaultArgs || devtoolsOptions.ignoreDefaultArgs
let headless = (chromeOptions as any).headless || devtoolsOptions.headless
const ignoreDefaultArgs = (capabilities as any).ignoreDefaultArgs || devtoolsOptions.ignoreDefaultArgs
const headless = (chromeOptions as any).headless || devtoolsOptions.headless

if (typeof mobileEmulation.deviceName === 'string') {
const deviceProperties = KnownDevices[mobileEmulation.deviceName as keyof typeof KnownDevices]
Expand Down Expand Up @@ -223,8 +225,8 @@ export default async function launch (capabilities: ExtendedCapabilities) {
* This fixes running e2e tests on Windows. For some reason within a Vitest environment
* capitalization matters for environment variables.
*/
if (!process.env.PROGRAMFILES && process.env['ProgramFiles']) {
process.env.PROGRAMFILES = process.env['ProgramFiles']
if (!process.env.PROGRAMFILES && process.env.ProgramFiles) {
process.env.PROGRAMFILES = process.env.ProgramFiles
}
const programFiles86 = process.env['ProgramFiles(X86)'] || process.env['ProgramFiles(x86)']
if (!process.env['PROGRAMFILES(X86)'] && programFiles86) {
Expand Down
6 changes: 3 additions & 3 deletions packages/devtools/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { EventEmitter } from 'node:events'
import type { EventEmitter } from 'node:events'

import type { Options, Capabilities } from '@wdio/types'
import type { ProtocolCommandsAsync } from '@wdio/protocols'
import { LaunchOptions, BrowserLaunchArgumentOptions, BrowserConnectOptions, ConnectOptions } from 'puppeteer-core'
import { EventEmitter as PuppeteerEventEmitter } from 'puppeteer-core/lib/cjs/puppeteer/common/EventEmitter.js'
import type { LaunchOptions, BrowserLaunchArgumentOptions, BrowserConnectOptions, ConnectOptions } from 'puppeteer-core'
import type { EventEmitter as PuppeteerEventEmitter } from 'puppeteer-core/lib/cjs/puppeteer/common/EventEmitter.js'
export interface ExtendedCapabilities extends Capabilities.Capabilities, WDIODevtoolsOptions {}

export interface WDIODevtoolsOptions {
Expand Down
6 changes: 4 additions & 2 deletions packages/devtools/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import which from 'which'
import logger from '@wdio/logger'
import { resolve } from 'import-meta-resolve'
import { commandCallStructure, isValidParameter, getArgumentType, canAccess } from '@wdio/utils'
import { WebDriverProtocol, CommandParameters, CommandPathVariables, ElementReference } from '@wdio/protocols'
import { launch as launchChromeBrowser, Options } from 'chrome-launcher'
import type { CommandParameters, CommandPathVariables, ElementReference } from '@wdio/protocols'
import { WebDriverProtocol } from '@wdio/protocols'
import type { Options } from 'chrome-launcher'
import { launch as launchChromeBrowser } from 'chrome-launcher'
import type { Logger } from '@wdio/logger/build/node'
import type { ElementHandle } from 'puppeteer-core/lib/cjs/puppeteer/common/ElementHandle'
import type { Browser } from 'puppeteer-core/lib/cjs/puppeteer/api/Browser'
Expand Down
4 changes: 2 additions & 2 deletions packages/devtools/tests/utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, it, expect, afterEach, vi, test } from 'vitest'

import path from 'node:path'
import type path from 'node:path'
// @ts-ignore no types needed
import debug from 'debug'
import which from 'which'
Expand Down Expand Up @@ -71,7 +71,7 @@ const command = {
}]
}

let pageMock = {
const pageMock = {
waitForSelector: vi.fn(),
waitForXPath: vi.fn(),
$$eval: vi.fn(),
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-plugin-wdio/src/rules/no-debug.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Rule } from 'eslint'
import type { Rule } from 'eslint'
import { isCommand } from '../utils/helpers.js'

const rule: Rule.RuleModule = {
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-plugin-wdio/src/rules/no-pause.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Rule } from 'eslint'
import type { Rule } from 'eslint'
import { isCommand } from '../utils/helpers.js'

const rule: Rule.RuleModule = {
Expand Down
13 changes: 8 additions & 5 deletions packages/wdio-allure-reporter/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
import { createRequire } from 'node:module'
import { stringify } from 'csv-stringify/sync'
import WDIOReporter, {
import type {
SuiteStats, Tag, HookStats, RunnerStats, TestStats, BeforeCommandArgs,
AfterCommandArgs, CommandArgs, Argument
} from '@wdio/reporter'
import WDIOReporter from '@wdio/reporter'
import type { Capabilities, Options } from '@wdio/types'

import {
getTestStatus, isEmpty, tellReporter, isMochaEachHooks, getErrorFromFailedTest,
isMochaAllHooks, getLinkByTemplate, attachConsoleLogs
} from './utils.js'
import { events, PASSED, PENDING, SKIPPED, stepStatuses } from './constants.js'
import {
import type {
AddAttachmentEventArgs, AddDescriptionEventArgs, AddEnvironmentEventArgs,
AddFeatureEventArgs, AddIssueEventArgs, AddLabelEventArgs, AddSeverityEventArgs,
AddStoryEventArgs, AddTestIdEventArgs, AllureReporterOptions, Status
AddStoryEventArgs, AddTestIdEventArgs, Status
} from './types.js'
import { AllureReporterOptions
} from './types.js'

const require = createRequire(import.meta.url)
Expand Down Expand Up @@ -56,7 +59,7 @@ class AllureReporter extends WDIOReporter {

this._lastScreenshot = undefined

let processObj:any = process
const processObj:any = process
if (options.addConsoleLogs || this._addConsoleLogs) {
processObj.stdout.write = (chunk: string, encoding: BufferEncoding, callback: ((err?: Error) => void)) => {
if (typeof chunk === 'string' && !chunk.includes('mwebdriver')) {
Expand Down Expand Up @@ -167,7 +170,7 @@ class AllureReporter extends WDIOReporter {

const testTitle = test.currentTest ? test.currentTest : test.title

if (this.isAnyTestRunning() && this._allure.getCurrentTest().name == testTitle) {
if (this.isAnyTestRunning() && this._allure.getCurrentTest().name === testTitle) {
// Test already in progress, most likely started by a before each hook
this.setCaseParameters(test.cid, test.parent)
return
Expand Down
4 changes: 2 additions & 2 deletions packages/wdio-allure-reporter/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import process from 'node:process'
import stripAnsi from 'strip-ansi'
import { HookStats, TestStats } from '@wdio/reporter'
import type { HookStats, TestStats } from '@wdio/reporter'
import type { Options } from '@wdio/types'

import CompoundError from './compoundError.js'
import { mochaEachHooks, mochaAllHooks, linkPlaceholder } from './constants.js'
import AllureReporter from './index.js'
import type AllureReporter from './index.js'
import type { Status } from './types'

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HookStats, SuiteStats, TestStats } from '@wdio/reporter'
import type { HookStats, SuiteStats, TestStats } from '@wdio/reporter'

const suite = (type = 'feature') => ({
type,
Expand Down
2 changes: 1 addition & 1 deletion packages/wdio-allure-reporter/tests/__fixtures__/runner.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { RunnerStats } from '@wdio/reporter'
import type { RunnerStats } from '@wdio/reporter'

const runner = (): RunnerStats => ({
type: 'runner',
Expand Down
2 changes: 1 addition & 1 deletion packages/wdio-allure-reporter/tests/allureFeatures.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import path from 'node:path'
import { describe, it, expect, beforeEach, vi, beforeAll, afterAll } from 'vitest'
import { CommandArgs, SuiteStats, TestStats } from '@wdio/reporter'
import type { CommandArgs, SuiteStats, TestStats } from '@wdio/reporter'
import AllureReporter from '../src/index.js'
import { linkPlaceholder } from '../src/constants.js'
import { TYPE } from '../src/types.js'
Expand Down
9 changes: 5 additions & 4 deletions packages/wdio-appium-service/src/launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ import fs from 'node:fs'
import fsp from 'node:fs/promises'
import url from 'node:url'
import path from 'node:path'
import { ChildProcessByStdio, spawn } from 'node:child_process'
import type { ChildProcessByStdio } from 'node:child_process'
import { spawn } from 'node:child_process'
import { promisify } from 'node:util'
import { Readable } from 'node:stream'
import type { Readable } from 'node:stream'

import logger from '@wdio/logger'
import { resolve } from 'import-meta-resolve'
Expand Down Expand Up @@ -125,7 +126,7 @@ export default class AppiumLauncher implements Services.ServiceInstance {

private _startAppium(command: string, args: Array<string>, callback: (err: any, result: any) => void): void {
log.debug(`Will spawn Appium process: ${command} ${args.join(' ')}`)
let process: ChildProcessByStdio<null, Readable, Readable> = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] })
const process: ChildProcessByStdio<null, Readable, Readable> = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] })
let error: Error | undefined

process.stdout.on('data', (data) => {
Expand All @@ -142,7 +143,7 @@ export default class AppiumLauncher implements Services.ServiceInstance {

process.once('exit', exitCode => {
let errorMessage = `Appium exited before timeout (exit code: ${exitCode})`
if (exitCode == 2) {
if (exitCode === 2) {
errorMessage += '\n' + (error || 'Check that you don\'t already have a running Appium service.')
log.error(errorMessage)
}
Expand Down
Loading

0 comments on commit 62e24d4

Please sign in to comment.