Skip to content

Commit

Permalink
fix(testing): fix eslint
Browse files Browse the repository at this point in the history
  • Loading branch information
christian-bromann committed Nov 18, 2024
1 parent 4e7bb26 commit bf55339
Show file tree
Hide file tree
Showing 37 changed files with 274 additions and 234 deletions.
2 changes: 1 addition & 1 deletion __mocks__/@wdio/globals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export function $$(selector) {
parent._length = length
els.parent = parent

els.foundWith = "$$"
els.foundWith = '$$'
// Required to check length prop
els.props = []
els.props.length = length
Expand Down
18 changes: 16 additions & 2 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,27 @@ import wdioEslint from '@wdio/eslint'

export default wdioEslint.config([
{
ignores: ['dist']
ignores: [
'lib',
'types'
]
},
/**
* custom test configuration
*/
{
files: ['tests/**/*'],
files: [
'test/**/*',
'__mocks__/**/*'
],
languageOptions: {
globals: {
beforeAll: true,
afterAll: true,
afterEach: true,
beforeEach: true
}
},
rules: {
'@typescript-eslint/no-require-imports': 'off',
'@typescript-eslint/no-explicit-any': 'off'
Expand Down
3 changes: 2 additions & 1 deletion jasmine.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/// <reference types="expect-webdriverio/types/expect-webdriverio"/>

declare module jasmine {
declare namespace jasmine {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface AsyncMatchers<T, U> extends ExpectWebdriverIO.Matchers<Promise<void>, T> {}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"clean:tests": "rimraf test-types/**/node_modules && rimraf test-types/**/dist",
"compile": "tsc --build tsconfig.build.json",
"test": "run-s test:*",
"test:lint": "eslint",
"test:lint": "eslint .",
"test:unit": "vitest --run",
"test:types": "node test-types/copy && npm run ts && npm run clean:tests",
"ts": "run-s ts:*",
Expand Down
6 changes: 4 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@ expectLib.extend = (m) => {
return extend(m)
}

expectLib.extend(wdioMatchers)
type MatchersObject = Parameters<typeof expectLib.extend>[0]

expectLib.extend(wdioMatchers as MatchersObject)
export const expect = expectLib as unknown as ExpectWebdriverIO.Expect
export const getConfig = (): any => DEFAULT_OPTIONS
export const getConfig = (): ExpectWebdriverIO.DefaultOptions => DEFAULT_OPTIONS
export const setDefaultOptions = (options = {}): void => {
Object.entries(options).forEach(([key, value]) => {
if (key in DEFAULT_OPTIONS) {
Expand Down
4 changes: 2 additions & 2 deletions src/matchers/element/toBeExisting.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ export async function toExist(
return result
}

export function toBeExisting(el: WdioElementMaybePromise, options?: ExpectWebdriverIO.CommandOptions): any {
export function toBeExisting(el: WdioElementMaybePromise, options?: ExpectWebdriverIO.CommandOptions) {
return aliasFn.call(this, toExist, { verb: 'be', expectation: 'existing' }, el, options)
}
export function toBePresent(el: WdioElementMaybePromise, options?: ExpectWebdriverIO.CommandOptions): any {
export function toBePresent(el: WdioElementMaybePromise, options?: ExpectWebdriverIO.CommandOptions) {
return aliasFn.call(this, toExist, { verb: 'be', expectation: 'present' }, el, options)
}
4 changes: 2 additions & 2 deletions src/matchers/element/toHaveAttribute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ async function conditionAttr(el: WebdriverIO.Element, attribute: string) {
const attr = await el.getAttribute(attribute)
if (typeof attr !== 'string') {
return { result: false, value: attr }
} else {
return { result: true, value: attr }
}
return { result: true, value: attr }

}

async function conditionAttrAndValue(el: WebdriverIO.Element, attribute: string, value: string | RegExp | ExpectWebdriverIO.PartialMatcher, options: ExpectWebdriverIO.StringOptions) {
Expand Down
4 changes: 2 additions & 2 deletions src/matchers/element/toHaveClass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ async function condition(el: WebdriverIO.Element, attribute: string, value: stri
return Array.isArray(value)
? compareTextWithArray(t, value, options).result
: compareText(t, value, options).result
});
})

return {
value: actualClass,
Expand All @@ -33,7 +33,7 @@ async function condition(el: WebdriverIO.Element, attribute: string, value: stri
/**
* @deprecated
*/
export function toHaveClass(...args: any): any {
export function toHaveClass(...args: unknown[]) {
return toHaveElementClass.call(this || {}, ...args)
}

Expand Down
6 changes: 3 additions & 3 deletions src/matchers/element/toHaveElementProperty.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
async function condition(
el: WebdriverIO.Element,
property: string,
value?: any,
value: unknown,
options: ExpectWebdriverIO.StringOptions = DEFAULT_OPTIONS
) {
const { asString = false } = options
Expand All @@ -31,7 +31,7 @@ async function condition(

prop = prop.toString()

return compareText(prop, value, options)
return compareText(prop, value as string | RegExp | ExpectWebdriverIO.PartialMatcher, options)
}

export async function toHaveElementProperty(
Expand All @@ -50,7 +50,7 @@ export async function toHaveElementProperty(
})

let el = await received?.getElement()
let prop: any
let prop: unknown
const pass = await waitUntil(
async () => {
const result = await executeCommand.call(this, el, condition, options, [property, value])
Expand Down
8 changes: 4 additions & 4 deletions src/matchers/element/toHaveSize.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { DEFAULT_OPTIONS } from '../../constants.js';
import type { WdioElementMaybePromise } from '../../types.js';
import { DEFAULT_OPTIONS } from '../../constants.js'
import type { WdioElementMaybePromise } from '../../types.js'
import {
compareObject,
enhanceError,
executeCommand,
waitUntil,
wrapExpectedWithArray,
} from '../../utils.js';
} from '../../utils.js'

async function condition(el: WebdriverIO.Element, size: { height: number; width: number }): Promise<any> {
async function condition(el: WebdriverIO.Element, size: { height: number; width: number }) {
const actualSize = await el.getSize()

return compareObject(actualSize, size)
Expand Down
6 changes: 3 additions & 3 deletions src/matchers/element/toHaveStyle.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { DEFAULT_OPTIONS } from '../../constants.js';
import type { WdioElementMaybePromise } from '../../types.js';
import { DEFAULT_OPTIONS } from '../../constants.js'
import type { WdioElementMaybePromise } from '../../types.js'
import {
compareStyle,
enhanceError,
executeCommand,
waitUntil,
wrapExpectedWithArray
} from '../../utils.js';
} from '../../utils.js'

async function condition(el: WebdriverIO.Element, style: { [key: string]: string; }, options: ExpectWebdriverIO.StringOptions) {
return compareStyle(el, style, options)
Expand Down
15 changes: 7 additions & 8 deletions src/matchers/element/toHaveText.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,31 @@
import type { ChainablePromiseElement, ChainablePromiseArray } from 'webdriverio'
import { DEFAULT_OPTIONS } from '../../constants.js';
import { DEFAULT_OPTIONS } from '../../constants.js'
import {
compareText, compareTextWithArray,
enhanceError,
executeCommand,
waitUntil,
wrapExpectedWithArray
} from '../../utils.js';
} from '../../utils.js'

async function condition(el: WebdriverIO.Element | WebdriverIO.ElementArray, text: string | RegExp | Array<string | RegExp> | ExpectWebdriverIO.PartialMatcher | Array<string | RegExp>, options: ExpectWebdriverIO.StringOptions) {
const actualTextArray: string[] = []
const resultArray: boolean[] = []
let checkAllValuesMatchCondition: boolean

if(Array.isArray(el)){
for(const element of el){
if (Array.isArray(el)){
for (const element of el){
const actualText = await element.getText()
actualTextArray.push(actualText)
const result = Array.isArray(text)
? compareTextWithArray(actualText, text, options).result
: compareText(actualText, text, options).result
resultArray.push(result)
}
checkAllValuesMatchCondition = resultArray.every(result => result)
}
else{
checkAllValuesMatchCondition = resultArray.every(result => result)
} else {
const actualText = await (el as WebdriverIO.Element).getText()
actualTextArray.push(actualText);
actualTextArray.push(actualText)
checkAllValuesMatchCondition = Array.isArray(text)
? compareTextWithArray(actualText, text, options).result
: compareText(actualText, text, options).result
Expand Down
2 changes: 1 addition & 1 deletion src/matchers/element/toHaveWidth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
wrapExpectedWithArray
} from '../../utils.js'

async function condition(el: WebdriverIO.Element, width: number): Promise<any> {
async function condition(el: WebdriverIO.Element, width: number) {
const actualWidth = await el.getSize('width')

return {
Expand Down
8 changes: 4 additions & 4 deletions src/matchers/elements/toBeElementsArrayOfSize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export async function toBeElementsArrayOfSize(
})

// type check
let numberOptions: ExpectWebdriverIO.NumberOptions;
let numberOptions: ExpectWebdriverIO.NumberOptions
if (typeof expectedValue === 'number') {
numberOptions = { eq: expectedValue } as ExpectWebdriverIO.NumberOptions
} else if (!expectedValue || (typeof expectedValue.eq !== 'number' && typeof expectedValue.gte !== 'number' && typeof expectedValue.lte !== 'number')) {
Expand All @@ -28,7 +28,7 @@ export async function toBeElementsArrayOfSize(
}

let elements = await received as WebdriverIO.ElementArray
const originalLength = elements.length;
const originalLength = elements.length
const pass = await waitUntil(async () => {
/**
* check numbers first before refetching elements
Expand All @@ -39,11 +39,11 @@ export async function toBeElementsArrayOfSize(
}
elements = await refetchElements(elements, numberOptions.wait, true)
return false
}, isNot, {...numberOptions, ...options})
}, isNot, { ...numberOptions, ...options })

if (Array.isArray(received) && pass) {
for (let index = originalLength; index < elements.length; index++) {
received.push(elements[index]);
received.push(elements[index])
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/matchers/mock/toBeRequested.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { toBeRequestedTimes } from './toBeRequestedTimes.js'
import { DEFAULT_OPTIONS } from '../../constants.js'

export function toBeRequested(received: WebdriverIO.Mock, options: ExpectWebdriverIO.CommandOptions = DEFAULT_OPTIONS): any {
export function toBeRequested(received: WebdriverIO.Mock, options: ExpectWebdriverIO.CommandOptions = DEFAULT_OPTIONS) {
return toBeRequestedTimes.call({ ...(this || {}), expectation: 'called' }, received, { gte: 1 }, options)
}
2 changes: 1 addition & 1 deletion src/matchers/mock/toBeRequestedTimes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export async function toBeRequestedTimes(
const pass = await waitUntil(async () => {
actual = received.calls.length
return compareNumbers(actual, numberOptions)
}, isNot, {...numberOptions, ...options})
}, isNot, { ...numberOptions, ...options })

const error = numberError(numberOptions)
const message = enhanceError('mock', error, actual, this, verb, expectation, '', numberOptions)
Expand Down
41 changes: 29 additions & 12 deletions src/matchers/mock/toBeRequestedWith.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ import { DEFAULT_OPTIONS } from '../../constants.js'
const STR_LIMIT = 80
const KEY_LIMIT = 12

interface RequestMock {
request: local.NetworkRequestData,
response: local.NetworkResponseData
}

function reduceHeaders(headers: local.NetworkHeader[]) {
return Object.entries(headers).reduce((acc, [, value]: [string, local.NetworkHeader]) => {
acc[value.name] = value.value.value
Expand All @@ -28,7 +33,7 @@ export async function toBeRequestedWith(
options,
})

let actual: any | undefined
let actual: RequestMock | undefined
const pass = await waitUntil(
async () => {
for (const call of received.calls) {
Expand All @@ -53,6 +58,10 @@ export async function toBeRequestedWith(
{ ...options, wait: isNot ? 0 : options.wait }
)

if (!actual) {
throw new Error('No request was made')

Check failure on line 62 in src/matchers/mock/toBeRequestedWith.ts

View workflow job for this annotation

GitHub Actions / linux (18.x)

test/matchers/mock/toBeRequestedWith.test.ts > toBeRequestedWith > wait for NOT success

Error: No request was made ❯ Object.toBeRequestedWith src/matchers/mock/toBeRequestedWith.ts:62:15 ❯ test/matchers/mock/toBeRequestedWith.test.ts:184:24

Check failure on line 62 in src/matchers/mock/toBeRequestedWith.ts

View workflow job for this annotation

GitHub Actions / linux (18.x)

test/matchers/mock/toBeRequestedWith.test.ts > toBeRequestedWith > message

Error: No request was made ❯ Object.toBeRequestedWith src/matchers/mock/toBeRequestedWith.ts:62:15 ❯ test/matchers/mock/toBeRequestedWith.test.ts:446:27

Check failure on line 62 in src/matchers/mock/toBeRequestedWith.ts

View workflow job for this annotation

GitHub Actions / linux (20.x)

test/matchers/mock/toBeRequestedWith.test.ts > toBeRequestedWith > wait for NOT success

Error: No request was made ❯ Object.toBeRequestedWith src/matchers/mock/toBeRequestedWith.ts:62:15 ❯ test/matchers/mock/toBeRequestedWith.test.ts:184:24

Check failure on line 62 in src/matchers/mock/toBeRequestedWith.ts

View workflow job for this annotation

GitHub Actions / linux (20.x)

test/matchers/mock/toBeRequestedWith.test.ts > toBeRequestedWith > message

Error: No request was made ❯ Object.toBeRequestedWith src/matchers/mock/toBeRequestedWith.ts:62:15 ❯ test/matchers/mock/toBeRequestedWith.test.ts:446:27

Check failure on line 62 in src/matchers/mock/toBeRequestedWith.ts

View workflow job for this annotation

GitHub Actions / linux (22.x)

test/matchers/mock/toBeRequestedWith.test.ts > toBeRequestedWith > wait for NOT success

Error: No request was made ❯ Object.toBeRequestedWith src/matchers/mock/toBeRequestedWith.ts:62:15 ❯ test/matchers/mock/toBeRequestedWith.test.ts:184:24

Check failure on line 62 in src/matchers/mock/toBeRequestedWith.ts

View workflow job for this annotation

GitHub Actions / linux (22.x)

test/matchers/mock/toBeRequestedWith.test.ts > toBeRequestedWith > message

Error: No request was made ❯ Object.toBeRequestedWith src/matchers/mock/toBeRequestedWith.ts:62:15 ❯ test/matchers/mock/toBeRequestedWith.test.ts:446:27
}

const message = enhanceError(
'mock',
minifyRequestedWith(expectedValue),
Expand Down Expand Up @@ -232,8 +241,16 @@ const headersMatcher = (
* jasmine.any and jasmine.anything don't have `sample` property
* @param filter
*/
const isMatcher = (filter: any) => {
return typeof filter.__proto__?.asymmetricMatch === 'function'
const isMatcher = (filter: unknown) => {
return (
typeof filter === 'object' &&
filter !== null &&
'__proto__' in filter &&
typeof filter.__proto__ === 'object' &&
filter.__proto__ &&
'asymmetricMatch' in filter.__proto__ &&
typeof filter.__proto__.asymmetricMatch === 'function'
)
}

// const tryParseBody = (jsonString: string | undefined, fallback: any = null) => {
Expand All @@ -258,7 +275,7 @@ const minifyRequestMock = (
return requestMock
}

const r: Record<string, any> = {
const r: Record<string, unknown> = {
url: requestMock.request.url,
method: requestMock.request.method,
requestHeaders: requestMock.request.headers,
Expand Down Expand Up @@ -338,20 +355,20 @@ const shortenJson = (
obj: ExpectWebdriverIO.JsonCompatible,
lengthLimit = STR_LIMIT * 2,
keyLimit = KEY_LIMIT
) => {
): ExpectWebdriverIO.JsonCompatible => {
if (JSON.stringify(obj).length < lengthLimit) {
return obj
return obj as ExpectWebdriverIO.JsonCompatible
}

if (Array.isArray(obj)) {
const firstItem: any =
const firstItem: object | string =
typeof obj[0] === 'object' && obj[0] !== null
? shortenJson(obj[0], lengthLimit / 2, keyLimit / 4)
: shortenString(JSON.stringify(obj[0]))
return [firstItem, `... ${obj.length - 1} more items`]
return [firstItem, `... ${obj.length - 1} more items`] as string[]
}

const minifiedObject: Record<string, any> = {}
const minifiedObject: Record<string, unknown> = {}
const entries = Object.entries(obj)

if (keyLimit >= 4) {
Expand All @@ -368,7 +385,7 @@ const shortenJson = (
minifiedObject['...'] = `${entries.length} items in total`
}

return minifiedObject
return minifiedObject as ExpectWebdriverIO.JsonCompatible
}

/**
Expand All @@ -379,14 +396,14 @@ const shortenString = (str: string, limit = STR_LIMIT) => {
return str.length > limit ? str.substring(0, limit / 2 - 1) + '..' + str.substr(1 - limit / 2) : str
}

const deleteUndefinedValues = (obj: Record<string, any>, baseline = obj) => {
const deleteUndefinedValues = (obj: Record<string, unknown>, baseline = obj) => {
Object.keys(obj).forEach((k) => {
if (typeof baseline[k] === 'undefined') {
delete obj[k]
}
})
}

export function toBeRequestedWithResponse(...args: any): any {
export function toBeRequestedWithResponse(...args: unknown[]) {
return toBeRequestedWith.call(this, ...args)
}
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ export type WdioElementsMaybePromise =
ChainablePromiseArray

export type RawMatcherFn<Context extends MatcherContext = MatcherContext> = {
(this: Context, actual: any, ...expected: Array<any>): ExpectationResult;
(this: Context, actual: unknown, ...expected: unknown[]): ExpectationResult;
}
2 changes: 1 addition & 1 deletion src/util/elementsUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @param actual actual result or results array
* @param expected expected result
*/
export const wrapExpectedWithArray = (el: WebdriverIO.Element | WebdriverIO.ElementArray, actual: any, expected: any) => {
export const wrapExpectedWithArray = (el: WebdriverIO.Element | WebdriverIO.ElementArray, actual: unknown, expected: unknown) => {
if (Array.isArray(el) && el.length > 1 && Array.isArray(actual)) {
expected = [expected]
}
Expand Down
Loading

0 comments on commit bf55339

Please sign in to comment.