WebdriverIO
How to use Multiple Cucumber HTML Reporter with WebdriverIO.
Integrating with WebdriverIO allows you to automatically generate beautiful HTML reports and capture screenshots on failure.
Tip
- Check out the example project under the
examples/wdiofolder in the reporter repository. - Refer to the GitHub Actions workflow for WebDriverIO to see how reports are generated across different approaches and CI jobs.
Recommended Approach: Use the mchr CLI
We strongly recommend using the mchr CLI alongside a .multiple-cucumber-html-reporter.yml configuration file to generate reports instead of invoking the programmatic generate() function in your WDIO hooks.
Running mchr as a standalone command separates test execution from report generation, keeps your WDIO configuration clean, and simplifies CI pipelines.
Approaches
There are two primary approaches for generating Cucumber report output with WebdriverIO:
- Cucumber In-built Formatter (Recommended): Uses native Cucumber formatting via
@wdio/cucumber-frameworkto generate Cucumber JSON and/or Cucumber Messages (.ndjson) files. Cucumber Messages provide rich metadata including scenario-level start and end timestamps. @wdio/cucumberjs-json-reporter: Uses the WDIO community reporter to output Cucumber JSON files.
Using Cucumber In-built Formatter (Recommended)
Install Dependencies
Ensure you have @wdio/cucumber-framework and multiple-cucumber-html-reporter installed:
npm install -D @wdio/cucumber-framework multiple-cucumber-html-reporterConfigure tsconfig.json
Ensure your TypeScript configuration includes Cucumber framework types:
// tsconfig.json
{
"compilerOptions": {
"types": [
"node",
"@wdio/globals/types",
"expect-webdriverio",
"@wdio/cucumber-framework"
]
}
}Configure Cucumber Options in WDIO
Configure formatters in cucumberOpts to output unique report files per worker instance:
// wdio-cc-formatter.conf.ts
import { config as sharedConfig } from './wdio-shared.conf';
export const config: WebdriverIO.Config = {
...sharedConfig,
cucumberOpts: {
...sharedConfig.cucumberOpts,
format: [
'progress',
`json:reports/json/cucumber-report-${process.env.WDIO_WORKER_ID || '0-0'}.json`,
`message:reports/messages/cucumber-message-${process.env.WDIO_WORKER_ID || '0-0'}.ndjson`,
],
},
};Worker ID
process.env.WDIO_WORKER_ID prevents parallel test workers from overwriting each other's report files.
Handle Failures & Capture Screenshots
Use a Cucumber After hook to capture screenshots on failure:
// src/steps/hooks.ts
import { After } from '@wdio/cucumber-framework';
import { browser } from '@wdio/globals';
After(async function ({ result }) {
if (result?.status === 'FAILED') {
const screenshot = await browser.takeScreenshot();
this.attach(Buffer.from(screenshot, 'base64'), 'image/png');
}
});Clean Reports Directory on Prepare
Ensure old reports and output files are removed before starting a new test run:
// wdio-shared.conf.ts
import { existsSync } from 'node:fs';
import { rm } from 'node:fs/promises';
export const config: WebdriverIO.Config = {
// ...
onPrepare: async () => {
if (existsSync('reports')) {
await rm('reports', { recursive: true });
}
},
// ...
};Parse Metadata & Update Feature URIs
When running parallel or multi-browser suites, capability metadata must be associated with the report files. You can use a helper (e.g. src/libs/metadata-parser.ts) to annotate feature titles and export a reports/metadata.json mapping:
// src/libs/metadata-parser.ts
import { readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { Metadata } from 'multiple-cucumber-html-reporter';
export function saveMetadata(
capabilities: (WebdriverIO.Capabilities & { 'cjson:metadata': Metadata })[]
): void {
const formatterFolder = process.env.MESSAGES || 'json';
const formatterExt = formatterFolder === 'messages' ? '.ndjson' : '.json';
const jsonDir = `./reports/${formatterFolder}/`;
const files = readdirSync(jsonDir).filter((file) => file.endsWith(formatterExt));
const customMetadata: Record<string, Metadata> = {};
files.forEach((file, index) => {
const filePath = join(jsonDir, file);
const rawData = readFileSync(filePath, 'utf-8');
const capability = capabilities[index];
if (!capability || !rawData.trim()) return;
const metadata = capability['cjson:metadata'];
const browserName = capability.browserName || 'chrome';
if (formatterFolder === 'messages') {
const lines = rawData.split('\n');
const updatedLines = lines.map((line) => {
if (!line.trim()) return line;
try {
const envelope = JSON.parse(line);
const updateUri = (uri: string): string => uri.replace('.feature', `-${browserName}.feature`);
if (envelope.source?.uri) envelope.source.uri = updateUri(envelope.source.uri);
if (envelope.gherkinDocument) {
if (envelope.gherkinDocument.uri) envelope.gherkinDocument.uri = updateUri(envelope.gherkinDocument.uri);
if (envelope.gherkinDocument.feature) {
envelope.gherkinDocument.feature.name = `${envelope.gherkinDocument.feature.name} [${browserName.toUpperCase()}]`;
}
const metaKey = envelope.gherkinDocument.uri?.split('/').pop();
if (metaKey) customMetadata[metaKey] = metadata;
}
if (envelope.pickle?.uri) envelope.pickle.uri = updateUri(envelope.pickle.uri);
return JSON.stringify(envelope);
} catch {
return line;
}
});
writeFileSync(filePath, updatedLines.join('\n'));
} else {
const suiteData = JSON.parse(rawData);
suiteData.forEach((feature: any) => {
feature.name = `${feature.name} [${browserName.toUpperCase()}]`;
feature.id = `${feature.id}-${browserName}`;
feature.uri = feature.uri.replace('.feature', `-${browserName}.feature`);
const metaKey = (feature.uri as string).split('/').pop();
if (metaKey) customMetadata[metaKey] = metadata;
});
writeFileSync(filePath, JSON.stringify(suiteData, null, 2));
}
});
writeFileSync(join(process.cwd(), 'reports', 'metadata.json'), JSON.stringify(customMetadata, null, 2), 'utf8');
}Invoke this helper in the onComplete hook:
// wdio-shared.conf.ts
import type { Metadata } from 'multiple-cucumber-html-reporter';
import { saveMetadata } from './src/libs/metadata-parser';
export const config: WebdriverIO.Config = {
// ...
onComplete: async (_exitCode, _config, capabilities, _results) => {
saveMetadata(capabilities as (WebdriverIO.Capabilities & { 'cjson:metadata': Metadata })[]);
},
};Using @wdio/cucumberjs-json-reporter
If you are using the community reporter @wdio/cucumberjs-json-reporter:
Install Dependency
npm install -D @wdio/cucumberjs-json-reporter multiple-cucumber-html-reporterConfigure Reporter in WDIO
// wdio-cc-reporter.conf.ts
import type { Metadata } from 'multiple-cucumber-html-reporter';
import { saveMetadata } from './src/libs/metadata-parser';
import { config as sharedConfig } from './wdio-shared.conf';
export const config: WebdriverIO.Config = {
...sharedConfig,
reporters: [
'spec',
[
'cucumberjs-json',
{
jsonFolder: 'reports/json',
},
],
],
onComplete: async (_exitCode, _config, capabilities, _results) => {
saveMetadata(capabilities as (WebdriverIO.Capabilities & { 'cjson:metadata': Metadata })[]);
},
};Attach Screenshots on Failure
// wdio-shared.conf.ts
import cucumberJson from '@wdio/cucumberjs-json-reporter';
export const config: WebdriverIO.Config = {
// ...
afterScenario: async (_world, result, _context) => {
if (!result.passed) {
cucumberJson.attach(await browser.takeScreenshot(), 'image/png');
}
},
};Configure mchr CLI
Create .multiple-cucumber-html-reporter.yml in your project root:
# .multiple-cucumber-html-reporter.yml
jsonDir: ./reports/${MESSAGES:'json'}
reportPath: ./reports/html
emailReport: true
openReportInBrowser: true
displayDuration: true
humanReadableDuration: true
displayReportTime: true
durationInMS: true
durationAggregation: sum
pageTitle: 'My WDIO Typescript Sample'
reportName: 'WDIO Cucumber JS Report'
metadataFilePath: ./reports/metadata.json
customData:
projectName: 'WebDriverIO sample project'
release: '1.2.0'
testCycle: ${GITHUB_RUN_ID:'Cycle 1'}
buildNumber: ${GITHUB_RUN_NUMBER:'Build 1'}
environment: 'production'
ciPipeline: 'GitHub Actions'Dynamic JSON Directory
The ${MESSAGES:'json'} syntax dynamically switches the input directory:
- When running with legacy JSON, it reads from
./reports/json. - When running with
MESSAGES=messages, it reads from./reports/messages.
Run Tests & Generate Reports
Configure your test scripts in package.json:
// package.json
{
"scripts": {
"test:formatter": "wdio run ./wdio-cc-formatter.conf.ts",
"test:reporter": "wdio run ./wdio-cc-reporter.conf.ts",
"report": "mchr"
}
}Run tests and invoke the mchr CLI:
pnpm test:formatter
pnpm reportWhy Avoid generate() Programmatically in WDIO Hooks?
In older versions or setups, it was common to import and call generate(...) inside the WDIO onComplete hook:
// ❌ Not recommended: Calling generate() inside onComplete
import { generate } from 'multiple-cucumber-html-reporter';
export const config: WebdriverIO.Config = {
onComplete: async () => {
await generate({
jsonDir: 'reports/json/',
reportPath: 'reports/html/',
// ...
});
},
};We advise against this approach because:
- Separation of Concerns: Test execution failure shouldn't prevent report generation, nor should report compilation issues interfere with test exit codes.
- Config Reusability: Storing your reporting setup in
.multiple-cucumber-html-reporter.ymlallows runningmchrlocally, in CI pipelines, and via CLI flags (-m,--override) without editing TypeScript files. - Support for Cucumber Messages: The
mchrCLI seamlessly supports NDJSON (-m) format, whereas invokinggenerate()directly requires manual message parsing setup.
Last updated on