From bf66e8ec0e6d51785e1ddff28f5f11b3b7691fac 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 590e1a91..217708ef 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() @@ -181,7 +216,7 @@ export async function reportSuiteSkipped( failure?: Frameworks.TestResult ): 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 055ffd30..dd87116d 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' @@ -114,6 +114,9 @@ export default class BrowserstackService implements Services.ServiceInstance { this._mochaBail = this._config?.framework === 'mocha' && Boolean(bailOpt) && !isFalse(bailOpt) const failHookAffectedTestsOpt: unknown = this._config?.mochaOpts?.failHookAffectedTests this._mochaFailHookAffectedTests = this._config?.framework === 'mocha' && failHookAffectedTestsOpt !== false + if (this._config?.framework === 'mocha') { + setMochaGrep(this._config.mochaOpts) + } PerformanceTester.startMonitoring('performance-report-service.csv') if (shouldProcessEventForTesthub('')) { From 9db565091f46aa0a6461e5acac1204458ceea78b Mon Sep 17 00:00:00 2001 From: Harshit Date: Tue, 1 Dec 2026 14:49:16 +0530 Subject: [PATCH 2/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 217708ef..9958ea18 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 73479890..dfcac883 100644 --- a/packages/browserstack-service/src/insights-handler.ts +++ b/packages/browserstack-service/src/insights-handler.ts @@ -45,6 +45,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' @@ -385,7 +386,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 6184b3ca19af758cb214e6cabbecdbfe121a10ec Mon Sep 17 00:00:00 2001 From: Harshit Date: Tue, 1 Dec 2026 15:03:52 +0530 Subject: [PATCH 3/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 9958ea18..a8b920e0 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 } From f4c928a35d8040510e7b86c51b2818ec3ced3637 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:08:00 +0000 Subject: [PATCH 4/4] chore(changeset): auto-generate from PR template (patch) --- .changeset/pr-400.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/pr-400.md diff --git a/.changeset/pr-400.md b/.changeset/pr-400.md new file mode 100644 index 00000000..e04a58e6 --- /dev/null +++ b/.changeset/pr-400.md @@ -0,0 +1,5 @@ +--- +"@wdio/browserstack-service": patch +--- + +- Fixed tests excluded by `mochaOpts.grep` being reported as skipped or failed when a hook failed during the run.