From f182a51928ebfd862a4cd5455d22a0eea3d51183 Mon Sep 17 00:00:00 2001 From: Harshit Date: Tue, 1 Dec 2026 13:56:32 +0530 Subject: [PATCH 1/4] fix(cli): keep grep-excluded tests out of the skipped-test cascade (SDK-8298) When a before/after-each hook fails or mocha bail fires, reportSuiteSkipped reports every test whose state is undefined as skipped. Mocha leaves tests its grep rejected in that same state and never reports them, so a --mochaOpts.grep rerun marked every excluded test as skipped, replacing its first-run result on the dashboard. Exclude tests that the active mochaOpts.grep / fgrep / invert rejects, compiled the same way Mocha 10 does. Tests the grep selected but a failed hook dropped are still reported. Co-Authored-By: Claude Opus 5.5 --- .../src/cli/skipReporter.ts | 37 ++++++++++++++++++- packages/browserstack-service/src/service.ts | 5 ++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/packages/browserstack-service/src/cli/skipReporter.ts b/packages/browserstack-service/src/cli/skipReporter.ts index b76ef1e7..36c333d7 100644 --- a/packages/browserstack-service/src/cli/skipReporter.ts +++ b/packages/browserstack-service/src/cli/skipReporter.ts @@ -21,9 +21,44 @@ 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: { pattern: RegExp, invert: boolean } | undefined + +// mirrors Mocha 10's constructor: `fgrep` (a literal string) 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 || {} + try { + if (typeof fgrep === 'string' && fgrep.length > 0) { + mochaGrep = { pattern: new RegExp(fgrep.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d')), invert } + } else if (grep instanceof RegExp) { + mochaGrep = { pattern: grep, invert } + } else if (typeof grep === 'string' && grep.length > 0) { + // Mocha.prototype.grep: a `/pattern/flags` string keeps its flags, anything else is the source + const arg = grep.match(/^\/(.*)\/([gimy]{0,4})$|.*/) as RegExpMatchArray + mochaGrep = { pattern: new RegExp(arg[1] || arg[0], arg[2]), invert } + } + } catch (err: unknown) { + BStackLogger.debug(`Ignoring mocha grep for skip reporting: ${err}`) + mochaGrep = undefined + } +} + +function isExcludedByGrep(t: MochaRuntimeTest): boolean { + if (!mochaGrep || typeof t.fullTitle !== 'function') { + return false + } + mochaGrep.pattern.lastIndex = 0 + const match = mochaGrep.pattern.test(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() @@ -175,7 +210,7 @@ export function reportSkippedTest( */ export async function reportSuiteSkipped(framework: TestFramework, suite: { tests?: unknown[], suites?: unknown[] }): Promise { for (const t of (suite.tests || []) as MochaRuntimeTest[]) { - if (t.state !== undefined) { + if (t.state !== undefined || isExcludedByGrep(t)) { continue } const parentTitle = t.parent?.title ?? '' diff --git a/packages/browserstack-service/src/service.ts b/packages/browserstack-service/src/service.ts index f00e434a..d17fb33c 100644 --- a/packages/browserstack-service/src/service.ts +++ b/packages/browserstack-service/src/service.ts @@ -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' @@ -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('')) { From 80c7121a2a4e0343f7066b98049af403a8f06bfc Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 08:28:17 +0000 Subject: [PATCH 2/4] chore(changeset): auto-generate from PR template (patch) --- .changeset/pr-398.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/pr-398.md diff --git a/.changeset/pr-398.md b/.changeset/pr-398.md new file mode 100644 index 00000000..72cd1684 --- /dev/null +++ b/.changeset/pr-398.md @@ -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. From 4e912039eb5f63c1c47fd5f86e828c3654bd46d7 Mon Sep 17 00:00:00 2001 From: Harshit Date: Tue, 1 Dec 2026 14:49:16 +0530 Subject: [PATCH 3/4] fix: apply the grep exclusion to the legacy skipped-test cascade (SDK-8298) insights-handler's hook-failure cascade, used when the CLI binary is not running, had the same `state === undefined` check and still reported grep-excluded tests as TestRunSkipped. Reuse isExcludedByGrep there. Co-Authored-By: Claude Opus 5.5 --- packages/browserstack-service/src/cli/skipReporter.ts | 2 +- packages/browserstack-service/src/insights-handler.ts | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/browserstack-service/src/cli/skipReporter.ts b/packages/browserstack-service/src/cli/skipReporter.ts index 36c333d7..8f258c00 100644 --- a/packages/browserstack-service/src/cli/skipReporter.ts +++ b/packages/browserstack-service/src/cli/skipReporter.ts @@ -50,7 +50,7 @@ export function setMochaGrep(mochaOpts?: { grep?: unknown, fgrep?: unknown, inve } } -function isExcludedByGrep(t: MochaRuntimeTest): boolean { +export function isExcludedByGrep(t: { fullTitle?: () => string }): boolean { if (!mochaGrep || typeof t.fullTitle !== 'function') { return false } diff --git a/packages/browserstack-service/src/insights-handler.ts b/packages/browserstack-service/src/insights-handler.ts index 02535d29..808224de 100644 --- a/packages/browserstack-service/src/insights-handler.ts +++ b/packages/browserstack-service/src/insights-handler.ts @@ -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' @@ -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(), From 81bb9547052bb9e88f8e08f5a242e780f0244451 Mon Sep 17 00:00:00 2001 From: Harshit Date: Tue, 1 Dec 2026 15:03:52 +0530 Subject: [PATCH 4/4] fix(cli): let the project's Mocha compile the grep for the skip cascade (SDK-8298) Building a RegExp from mochaOpts.grep in the service duplicated Mocha's conversion and needed a non-literal RegExp. fgrep is now a substring match, and a string grep is compiled by the project's own Mocha (Mocha.prototype.grep), so the cascade uses exactly the pattern the runner applies. If Mocha cannot be resolved, the cascade keeps today's behaviour. Co-Authored-By: Claude Opus 5.5 --- .../src/cli/skipReporter.ts | 71 ++++++++++++++----- 1 file changed, 55 insertions(+), 16 deletions(-) diff --git a/packages/browserstack-service/src/cli/skipReporter.ts b/packages/browserstack-service/src/cli/skipReporter.ts index 8f258c00..9c8671e7 100644 --- a/packages/browserstack-service/src/cli/skipReporter.ts +++ b/packages/browserstack-service/src/cli/skipReporter.ts @@ -1,4 +1,5 @@ import path from 'node:path' +import { createRequire } from 'node:module' import type { Frameworks } from '@wdio/types' @@ -27,26 +28,65 @@ interface MochaRuntimeTest { // 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: { pattern: RegExp, invert: boolean } | undefined +let mochaGrep: { matches: (title: string) => boolean, invert: boolean } | undefined -// mirrors Mocha 10's constructor: `fgrep` (a literal string) is applied after `grep` and wins +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 || {} - try { - if (typeof fgrep === 'string' && fgrep.length > 0) { - mochaGrep = { pattern: new RegExp(fgrep.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d')), invert } - } else if (grep instanceof RegExp) { - mochaGrep = { pattern: grep, invert } - } else if (typeof grep === 'string' && grep.length > 0) { - // Mocha.prototype.grep: a `/pattern/flags` string keeps its flags, anything else is the source - const arg = grep.match(/^\/(.*)\/([gimy]{0,4})$|.*/) as RegExpMatchArray - mochaGrep = { pattern: new RegExp(arg[1] || arg[0], arg[2]), invert } + 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}`) } - } catch (err: unknown) { - BStackLogger.debug(`Ignoring mocha grep for skip reporting: ${err}`) - mochaGrep = undefined } } @@ -54,8 +94,7 @@ export function isExcludedByGrep(t: { fullTitle?: () => string }): boolean { if (!mochaGrep || typeof t.fullTitle !== 'function') { return false } - mochaGrep.pattern.lastIndex = 0 - const match = mochaGrep.pattern.test(t.fullTitle()) + const match = mochaGrep.matches(t.fullTitle()) return mochaGrep.invert ? match : !match }