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. diff --git a/packages/browserstack-service/src/cli/skipReporter.ts b/packages/browserstack-service/src/cli/skipReporter.ts index b76ef1e7..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' @@ -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() @@ -175,7 +249,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/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(), 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('')) {