Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/pr-398.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@wdio/browserstack-service": patch
---

- Fixed tests excluded by `mochaOpts.grep` being reported as skipped when a hook failed during the run.
76 changes: 75 additions & 1 deletion packages/browserstack-service/src/cli/skipReporter.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import path from 'node:path'
import { createRequire } from 'node:module'

import type { Frameworks } from '@wdio/types'

Expand All @@ -21,9 +22,82 @@ interface MochaRuntimeTest {
state?: string
body?: string
file?: string
fullTitle?: () => string
parent?: { title?: string, parent?: unknown, tests?: unknown[], suites?: unknown[] }
}

// mocha skips grep-rejected tests silently: their `state` stays undefined exactly like a test
// dropped by a failed hook, so the suite cascade must exclude them itself
let mochaGrep: { matches: (title: string) => boolean, invert: boolean } | undefined

interface MochaGrepTarget {
options: { grep?: unknown }
grep: (re: string) => unknown
}

// mocha is a dependency of the project's @wdio/mocha-framework, not of this service
function loadMochaPrototype(): MochaGrepTarget | undefined {
for (const base of [path.join(process.cwd(), 'package.json'), import.meta.url]) {
try {
const Mocha = createRequire(base)('mocha') as { prototype?: MochaGrepTarget }
if (typeof Mocha?.prototype?.grep === 'function') {
return Mocha.prototype
}
} catch {
// not resolvable from this location
}
}
return undefined
}

// the project's own Mocha builds the pattern, so it matches what the runner applies
function compileWithMocha(grep: string): RegExp | undefined {
const proto = loadMochaPrototype()
if (!proto) {
return undefined
}
const target = Object.create(proto) as MochaGrepTarget
target.options = {}
target.grep(grep)
return target.options.grep instanceof RegExp ? target.options.grep : undefined
}

function regexMatcher(pattern: RegExp) {
return (title: string) => {
pattern.lastIndex = 0
return pattern.test(title)
}
}

// mirrors Mocha's constructor: `fgrep` (a literal substring) is applied after `grep` and wins
export function setMochaGrep(mochaOpts?: { grep?: unknown, fgrep?: unknown, invert?: unknown }) {
mochaGrep = undefined
const invert = Boolean(mochaOpts?.invert)
const { grep, fgrep } = mochaOpts || {}
if (typeof fgrep === 'string' && fgrep.length > 0) {
mochaGrep = { matches: (title) => title.includes(fgrep), invert }
} else if (grep instanceof RegExp) {
mochaGrep = { matches: regexMatcher(grep), invert }
} else if (typeof grep === 'string' && grep.length > 0) {
try {
const pattern = compileWithMocha(grep)
if (pattern) {
mochaGrep = { matches: regexMatcher(pattern), invert }
}
} catch (err: unknown) {
BStackLogger.debug(`Ignoring mocha grep for skip reporting: ${err}`)
}
}
}

export function isExcludedByGrep(t: { fullTitle?: () => string }): boolean {
if (!mochaGrep || typeof t.fullTitle !== 'function') {
return false
}
const match = mochaGrep.matches(t.fullTitle())
return mochaGrep.invert ? match : !match
}

// tests that entered the CLI beforeTest lifecycle — those report their own finish
// (including runtime `this.skip()` inside a test body) and must not be re-reported
const startedTests = new Set<string>()
Expand Down Expand Up @@ -175,7 +249,7 @@ export function reportSkippedTest(
*/
export async function reportSuiteSkipped(framework: TestFramework, suite: { tests?: unknown[], suites?: unknown[] }): Promise<void> {
for (const t of (suite.tests || []) as MochaRuntimeTest[]) {
if (t.state !== undefined) {
if (t.state !== undefined || isExcludedByGrep(t)) {
continue
}
const parentTitle = t.parent?.title ?? ''
Expand Down
3 changes: 2 additions & 1 deletion packages/browserstack-service/src/insights-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import type { Capabilities } from '@wdio/types'
import Listener from './testOps/listener.js'
import { TESTOPS_SCREENSHOT_ENV } from './constants.js'
import { BrowserstackCLI } from './cli/index.js'
import { isExcludedByGrep } from './cli/skipReporter.js'
import { TestFrameworkState } from './cli/states/testFrameworkState.js'
import { HookState } from './cli/states/hookState.js'
import { TestFrameworkConstants } from './cli/frameworks/constants/testFrameworkConstants.js'
Expand Down Expand Up @@ -386,7 +387,7 @@ class _InsightsHandler {
const sendTestSkip = async (skippedTest: any) => {

// We only need to send the tests that whose state is not determined yet. The state of tests which is determined will already be sent.
if (skippedTest.state === undefined) {
if (skippedTest.state === undefined && !isExcludedByGrep(skippedTest)) {
const fullTitle = `${skippedTest.parent.title} - ${skippedTest.title}`
this._tests[fullTitle] = {
uuid: uuidv4(),
Expand Down
5 changes: 4 additions & 1 deletion packages/browserstack-service/src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import PerformanceTester from './instrumentation/performance/performance-tester.
import * as PERFORMANCE_SDK_EVENTS from './instrumentation/performance/constants.js'
import { EVENTS } from './instrumentation/performance/constants.js'
import { BrowserstackCLI } from './cli/index.js'
import { drainSkipReports, markTestStarted, reportSuiteSkipped } from './cli/skipReporter.js'
import { drainSkipReports, markTestStarted, reportSuiteSkipped, setMochaGrep } from './cli/skipReporter.js'
import { CLIUtils } from './cli/cliUtils.js'

import { _fetch as fetch } from './fetchWrapper.js'
Expand Down Expand Up @@ -109,6 +109,9 @@ export default class BrowserstackService implements Services.ServiceInstance {
// strict 'true' string compare and would miss a numeric `bail: 1`
const bailOpt: unknown = this._config?.mochaOpts?.bail
this._mochaBail = this._config?.framework === 'mocha' && Boolean(bailOpt) && !isFalse(bailOpt)
if (this._config?.framework === 'mocha') {
setMochaGrep(this._config.mochaOpts)
}

PerformanceTester.startMonitoring('performance-report-service.csv')
if (shouldProcessEventForTesthub('')) {
Expand Down
Loading