### Plugin with Async Setup and Teardown Source: https://github.com/cucumber/cucumber-js/blob/main/docs/plugins.md Example of a plugin that performs asynchronous setup at the start and asynchronous teardown before Cucumber exits. The cleanup function is returned by the coordinator. ```js export default { type: 'plugin', coordinator: async (context) => { // this runs at the start await doSomeAsyncSetup() return async () => { // this runs at the end await doSomeAsyncTeardown() } } } ``` -------------------------------- ### Minimal Example Source: https://github.com/cucumber/cucumber-js/blob/main/docs/javascript_api.md A minimal example demonstrating how to load configuration and run Cucumber using the JavaScript API. ```APIDOC ## Minimal Example ```javascript import { loadConfiguration, runCucumber } from '@cucumber/cucumber/api' const { runConfiguration } = await loadConfiguration() const { success } = await runCucumber(runConfiguration) console.log(success) ``` ``` -------------------------------- ### YAML Configuration Example Source: https://github.com/cucumber/cucumber-js/blob/main/docs/configuration.md The equivalent configuration to the JSON example, but written in YAML format. Useful for human-readable configuration. ```yaml default: parallel: 2 format: - "html:cucumber-report.html" ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/cucumber/cucumber-js/blob/main/CONTRIBUTING.md Install project dependencies and run the test suite to ensure a working development environment. ```bash npm install npm test ``` -------------------------------- ### Run Configuration Example Source: https://github.com/cucumber/cucumber-js/blob/main/docs/javascript_api.md An example of a 'run' configuration object, which is more structured and required by the `runCucumber` function. ```json { "sources": { "defaultDialect": "en", "paths": [ "features/**/*.feature" ], "name": [], "tagExpression": "@interesting", "order": "defined" }, "support": { "importPaths": [ "features/support/**/*.js" ], "requireModules": [], "requirePaths": [] }, "formats": { "files": { "./reports/cucumber.html": "html" }, "options": {}, "publish": false, "stdout": "progress-bar" }, "runtime": { "dryRun": false, "failFast": true, "filterStacktraces": false, "parallel": 3, "retry": 2, "retryTagFilter": "@flaky", "strict": true, "worldParameters": {} } } ``` -------------------------------- ### Synchronous and Asynchronous BeforeAll/AfterAll Hooks Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/hooks.md Provides examples of synchronous, asynchronous callback, and asynchronous promise-based BeforeAll and AfterAll hooks for global setup and teardown. ```javascript const {AfterAll, BeforeAll} = require('@cucumber/cucumber'); // Synchronous BeforeAll(function () { // perform some shared setup }); // Asynchronous Callback BeforeAll(function (callback) { // perform some shared setup // execute the callback (optionally passing an error when done) }); // Asynchronous Promise AfterAll(function () { // perform some shared teardown return Promise.resolve() }); ``` -------------------------------- ### User Configuration Example Source: https://github.com/cucumber/cucumber-js/blob/main/docs/javascript_api.md An example of a 'user' configuration object, representing a simple, flat format used in configuration files and on the CLI. ```json { "backtrace": true, "dryRun": false, "forceExit": false, "failFast": true, "format": [ "progress-bar", ["html", "./reports/cucumber.html"] ], "formatOptions": {}, "import": ["features/support/**/*.js"], "language": "en", "name": [], "order": "defined", "paths": ["features/**/*.feature"], "parallel": 3, "publish": false, "require": [], "requireModule": [], "retry": 2, "retryTagFilter": "@flaky", "strict": true, "tags": "@interesting", "worldParameters": {} } ``` -------------------------------- ### Install Cucumber.js Source: https://github.com/cucumber/cucumber-js/blob/main/README.md Install Cucumber.js using npm. This is the first step to begin using Cucumber for your Node.js projects. ```shell npm install @cucumber/cucumber ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/cucumber/cucumber-js/blob/main/docs/configuration.md A basic configuration object in JSON format. This sets up parallel execution and HTML report generation. ```json { "default": { "parallel": 2, "format": ["html:cucumber-report.html"] } } ``` -------------------------------- ### JavaScript (CommonJS) Configuration Example Source: https://github.com/cucumber/cucumber-js/blob/main/docs/configuration.md Configuration defined using CommonJS module syntax. Standard for many Node.js projects. ```js module.exports = { default: { parallel: 2, format: ['html:cucumber-report.html'] } } ``` -------------------------------- ### Calculating a Test Plan Source: https://github.com/cucumber/cucumber-js/blob/main/docs/javascript_api.md Example demonstrating how to use `loadSources` to load, parse feature files, and calculate the test plan. ```APIDOC ## Calculating a Test Plan ```javascript import { loadConfiguration, loadSources } from '@cucumber/cucumber/api' const { runConfiguration } = await loadConfiguration() const { plan } = await loadSources(runConfiguration.sources) console.dir(plan) ``` ``` -------------------------------- ### Install tsx for TypeScript Transpilation Source: https://github.com/cucumber/cucumber-js/blob/main/docs/transpiling.md Install tsx as a development dependency to enable on-the-fly TypeScript compilation. ```shell npm install --save-dev tsx ``` -------------------------------- ### Main Application Code Source: https://github.com/cucumber/cucumber-js/blob/main/README.md Example of main application code that will be tested. This code defines a simple Greeter class. ```javascript class Greeter { sayHello() { return 'hello' } } module.exports = { Greeter } ``` -------------------------------- ### Calculate Test Plan Example Source: https://github.com/cucumber/cucumber-js/blob/main/docs/javascript_api.md This snippet shows how to use `loadSources` to parse feature files, calculate the test plan, and report parse errors. ```javascript import { loadConfiguration, loadSources } from '@cucumber/cucumber/api' const { runConfiguration } = await loadConfiguration() const { plan } = await loadSources(runConfiguration.sources) console.dir(plan) ``` -------------------------------- ### ESM Support Code Example Source: https://github.com/cucumber/cucumber-js/blob/main/docs/esm.md Example of support code (steps) written using ES Modules syntax. Ensure files have an `.mjs` extension or are configured for ESM. ```javascript // features/support/steps.mjs import { Given, When, Then } from '@cucumber/cucumber' import { strict as assert } from 'assert' Given('a variable set to {int}', function (number) { this.setTo(number) }) When('I increment the variable by {int}', function (number) { this.incrementBy(number) }) Then('the variable should contain {int}', function (number) { assert.equal(this.variable, number) }) ``` -------------------------------- ### Synchronous and Asynchronous Hooks Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/hooks.md Demonstrates synchronous, asynchronous callback, and asynchronous promise-based hooks for setup and teardown. ```javascript const {After, Before} = require('@cucumber/cucumber'); // Synchronous Before(function () { this.count = 0; }); // Asynchronous Callback Before(function (testCase, callback) { var world = this; tmp.dir({unsafeCleanup: true}, function(error, dir) { if (error) { callback(error); } else { world.tmpDir = dir; callback(); } }); }); // Asynchronous Promise After(function () { // Assuming this.driver is a selenium webdriver return this.driver.quit(); }); ``` -------------------------------- ### Install Cucumber.js with Yarn Source: https://github.com/cucumber/cucumber-js/blob/main/docs/installation.md Use this command to install the Cucumber.js package if you are using Yarn as your package manager. ```shell yarn add @cucumber/cucumber ``` -------------------------------- ### Feature File Example Source: https://github.com/cucumber/cucumber-js/blob/main/README.md A Gherkin feature file defining a scenario for testing the Greeter class. This describes the behavior in plain language. ```gherkin Feature: Greeting Scenario: Say hello When the greeter says hello Then I should have heard "hello" ``` -------------------------------- ### JavaScript (ESM) Configuration Example Source: https://github.com/cucumber/cucumber-js/blob/main/docs/configuration.md Configuration defined using modern JavaScript ES Modules syntax. Suitable for projects using ESM. ```js export default { parallel: 2, format: ['html:cucumber-report.html'] } ``` -------------------------------- ### Example of Multiple Attachments in a Step Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/attachments.md Demonstrates attaching different types of data (text, JSON, image) within a single step definition. ```javascript // Step definition Given('a basic step', async function() { this.attach('Some info.') this.attach('{"some": "JSON"}}', { mediaType: 'application/json' }) this.attach((await driver.takeScreenshot()), { mediaType: 'base64:image/png', fileName: 'screenshot.png' }) }) ``` -------------------------------- ### Minimal JavaScript API Example Source: https://github.com/cucumber/cucumber-js/blob/main/docs/javascript_api.md This snippet demonstrates the basic usage of the JavaScript API to load configuration and run Cucumber tests. ```javascript import { loadConfiguration, runCucumber } from '@cucumber/cucumber/api' const { runConfiguration } = await loadConfiguration() const { success } = await runCucumber(runConfiguration) console.log(success) ``` -------------------------------- ### Display Help for Cucumber.js CLI Source: https://github.com/cucumber/cucumber-js/blob/main/docs/cli.md View all available command-line options for your installed version of Cucumber.js. ```shell cucumber-js --help ``` -------------------------------- ### Tagged BeforeStep and AfterStep Hooks Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/hooks.md Demonstrates using tagged hooks for BeforeStep and AfterStep, including an example of taking a screenshot on step failure. ```javascript const {AfterStep, BeforeStep} = require('@cucumber/cucumber'); BeforeStep({tags: "@foo"}, function () { // This hook will be executed before all steps in a scenario with tag @foo }); AfterStep( function ({result}) { // This hook will be executed after all steps, and take a screenshot on step failure if (result.status === Status.FAILED) { this.driver.takeScreenshot(); } }); ``` -------------------------------- ### TypeScript Formatter Example Source: https://github.com/cucumber/cucumber-js/blob/main/docs/custom_formatters.md An example of a custom formatter written in TypeScript, utilizing the FormatterPlugin type for type checking and completion. It demonstrates how to define custom options and integrate them. ```typescript import type { FormatterPlugin } from '@cucumber/cucumber/api' type MyFormatterOptions = { foo: { bar: number } } const myFormatter: FormatterPlugin = { type: 'formatter', formatter: (context) => {...}, optionsKey: 'foo' } export default myFormatter ``` -------------------------------- ### Display Cucumber Version Source: https://github.com/cucumber/cucumber-js/blob/main/features/cli.feature.md Use the --version flag to display the installed version of Cucumber.js. ```bash cucumber-js --version ``` -------------------------------- ### Run Cucumber.js with npx Source: https://github.com/cucumber/cucumber-js/blob/main/docs/cli.md Use npx to execute Cucumber.js without global installation. ```shell npx cucumber-js ``` -------------------------------- ### Attach Binary Data from Stream (Await Promise) Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/attachments.md Attach binary data, like screenshots, from a stream. This example uses `async/await` to wait for the stream to be read. ```javascript var {After, Status} = require('@cucumber/cucumber'); // Awaiting the promise After(async function (testCase) { if (testCase.result.status === Status.FAILED) { var stream = getScreenshotOfError(); await this.attach(stream, { mediaType: 'image/png' }); } }); ``` -------------------------------- ### Usage Formatter Output Example Source: https://github.com/cucumber/cucumber-js/blob/main/docs/formatters.md The Usage Formatter displays step definitions, their usage in scenarios, execution durations, and identifies unused steps. This output is useful for understanding test coverage and performance. ```text ┌───────────────────────────────────────┬──────────┬─────────────────────────────────┐ │ Pattern / Text │ Duration │ Location │ ├───────────────────────────────────────┼──────────┼─────────────────────────────────┤ │ an empty todo list │ 760.33ms │ support/steps/steps.ts:6 │ │ an empty todo list │ 820ms │ features/empty.feature:4 │ │ an empty todo list │ 761ms │ features/adding-todos.feature:4 │ │ an empty todo list │ 700ms │ features/empty.feature:4 │ ├───────────────────────────────────────┼──────────┼─────────────────────────────────┤ │ I add the todo {string} │ 432.00ms │ support/steps/steps.ts:10 │ │ I add the todo "buy some cheese" │ 432ms │ features/adding-todos.feature:5 │ ├───────────────────────────────────────┼──────────┼─────────────────────────────────┤ │ my cursor is ready to create a todo │ 53.00ms │ support/steps/steps.ts:27 │ │ my cursor is ready to create a todo │ 101ms │ features/empty.feature:10 │ │ my cursor is ready to create a todo │ 5ms │ features/adding-todos.feature:8 │ ├───────────────────────────────────────┼──────────┼─────────────────────────────────┤ │ no todos are listed │ 46.00ms │ support/steps/steps.ts:15 │ │ no todos are listed │ 46ms │ features/empty.feature:7 │ ├───────────────────────────────────────┼──────────┼─────────────────────────────────┤ │ the todos are: │ 31.00ms │ support/steps/steps.ts:21 │ │ the todos are: │ 31ms │ features/adding-todos.feature:6 │ ├───────────────────────────────────────┼──────────┼─────────────────────────────────┤ │ I remove the todo {string} │ UNUSED │ support/steps/steps.ts:33 │ └───────────────────────────────────────┴──────────┴─────────────────────────────────┘ ``` -------------------------------- ### TypeScript Configuration Example Source: https://github.com/cucumber/cucumber-js/blob/main/docs/configuration.md Configuration file written in TypeScript, leveraging Node.js's built-in TS support. Requires explicit type imports and may have tsconfig.json limitations. ```typescript import type { IConfiguration } from '@cucumber/cucumber' export default { parallel: 2, format: ['html:cucumber-report.html'] } satisfies Partial ``` -------------------------------- ### Custom World with Plain Function Constructor Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/world.md Alternatively, use a plain function as a World constructor. This example initializes a `count` and an `eat` function. ```javascript const { setWorldConstructor, When } = require('@cucumber/cucumber') setWorldConstructor(function(options) { this.count = 0 this.eat = (count) => this.count += count }) When('I eat {int} cucumbers', function(count) { this.eat(count) }) ``` -------------------------------- ### Diagnose Duplicate Dependencies with npm Source: https://github.com/cucumber/cucumber-js/blob/main/docs/installation.md Run this command to identify if your project has duplicate installations of the @cucumber/cucumber package, which can lead to invalid installations. The output shows how different parts of your project depend on the package. ```shell npm why @cucumber/cucumber ``` -------------------------------- ### TypeScript Plugin with Typed Options Source: https://github.com/cucumber/cucumber-js/blob/main/docs/plugins.md This TypeScript example demonstrates how to define a plugin with explicit types for its options, ensuring type safety and autocompletion. ```typescript import type { Plugin } from '@cucumber/cucumber/api' type MyPluginOptions = { foo: { bar: number } } const myPlugin: Plugin = { type: 'plugin', coordinator: (context) => {...}, optionsKey: 'foo' } export default myPlugin ``` -------------------------------- ### Generator Function Step Definition with Wrapper Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/step_definitions.md Demonstrates wrapping generator functions for asynchronous operations using `setDefinitionFunctionWrapper`. This example uses `mz/fs` and `bluebird` for promise-based generator handling. ```javascript // features/step_definitions/file_steps.js const { Then } = require('@cucumber/cucumber'); const assert = require('assert'); const mzFs = require('mz/fs'); Then(/^the file named (.*) is empty$/, function *(fileName) { contents = yield mzFs.readFile(fileName, 'utf8'); assert.equal(contents, ''); }); // features/support/setup.js const { setDefinitionFunctionWrapper } = require('@cucumber/cucumber'); const isGenerator = require('is-generator'); const Promise = require('bluebird'); setDefinitionFunctionWrapper(function (fn) { if (isGenerator.fn(fn)) { return Promise.coroutine(fn); } else { return fn; } }); ``` -------------------------------- ### Basic World Usage for State Retention Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/world.md Use `this` to store and retrieve variables between steps within a scenario. This example demonstrates setting a color in one step and asserting it in another. ```javascript const { Given, Then } = require('@cucumber/cucumber') Given("my color is {string}", function(color) { this.color = color }) Then("my color should not be red", function() { if (this.color === "red") { throw new Error("Wrong Color"); } }); ``` -------------------------------- ### Command Line Invocation Example Source: https://github.com/cucumber/cucumber-js/blob/main/docs/deprecations.md Shows a command line invocation for cucumber-js that includes a specific feature file. This is used in conjunction with configuration file paths to demonstrate the merging behavior. ```shell cucumber-js features/auth.feature ``` -------------------------------- ### Install/Uninstall Cucumber.js Packages Source: https://github.com/cucumber/cucumber-js/blob/main/UPGRADING.md This shell command demonstrates how to remove the old 'cucumber' package and install the new '@cucumber/cucumber' package, necessary for version 7.0.0 and later. ```shell $ npm rm cucumber $ npm install --save-dev @cucumber/cucumber ``` -------------------------------- ### Custom World Implementation Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/world.md Extend the built-in `World` class to add custom methods and properties to the scenario scope. This example adds a `count` property and an `eat` method. ```javascript const { setWorldConstructor, World, When } = require('@cucumber/cucumber') class CustomWorld extends World { count = 0 constructor(options) { super(options) } eat(count) { this.count += count } } setWorldConstructor(CustomWorld) When('I eat {int} cucumbers', function(count) { this.eat(count) }) ``` -------------------------------- ### Configure Generator Snippet Interface Source: https://github.com/cucumber/cucumber-js/blob/main/UPGRADING.md In versions prior to 8.0.0, 'generator' was a supported snippet interface. This configuration example shows the old format. Update to 'synchronous', 'async-await', 'promise', or 'callback'. ```json { "formatOptions": { "snippetInterface": "generator" } } ``` -------------------------------- ### Referencing Custom Formatters Source: https://github.com/cucumber/cucumber-js/blob/main/UPGRADING.md Use this command to specify a custom formatter package or module name. Ensure local formatters use a relative path starting with './'. ```shell $ cucumber-js --format @cucumber/pretty-formatter ``` -------------------------------- ### Distribute Tests Across CI Jobs with GitHub Actions Source: https://github.com/cucumber/cucumber-js/blob/main/docs/sharding.md This example demonstrates how to use sharding with GitHub Actions to distribute test runs across multiple parallel jobs. Each job runs a specific shard of the test suite. ```yaml jobs: test: strategy: matrix: shard: [1, 2, 3] steps: - uses: actions/checkout@v4 - run: npm ci - run: npm test -- --shard ${{ matrix.shard }}/3 ``` -------------------------------- ### Setting Up Custom World and Before Hook Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/world.md Configure Cucumber.js to use your custom World class and set up a Before hook to initialize it. This ensures that each scenario starts with a fresh instance of your custom World. ```javascript // setup.js import { Before, setWorldConstructor } from '@cucumber/cucumber'; import CustomWorld from "../classes/CustomWorld.js" setWorldConstructor(CustomWorld); Before(async function(scenario) { await this.init(scenario); }); ``` -------------------------------- ### Worker Options Configuration Source: https://github.com/cucumber/cucumber-js/blob/main/docs/parallel.md Tune worker threads using the `workerOptions` configuration, which are passed to the Node.js `Worker` constructor. This example sets a resource limit for the old generation heap size. ```json { "parallel": 4, "workerOptions": { "resourceLimits": { "maxOldGenerationSizeMb": 2048 } } } ``` -------------------------------- ### Invoke Profile from Command Line Source: https://github.com/cucumber/cucumber-js/blob/main/docs/profiles.md Use the --profile option followed by the profile name to activate a specific configuration set. ```shell cucumber-js --profile my_profile ``` -------------------------------- ### Custom Work Assignment Logic Source: https://github.com/cucumber/cucumber-js/blob/main/docs/parallel.md Prevent specific scenarios from running in parallel by implementing a custom assignment function using `setParallelCanAssign`. This example ensures only one scenario with 'example' in its name runs at a time. ```javascript setParallelCanAssign(function (pickleInQuestion, picklesInProgress) { // Only one pickle with the word example in the name can run at a time if (pickleInQuestion.name.includes('example')) { return picklesInProgress.every((p) => !p.name.includes('example')) } // No other restrictions return true }) ``` -------------------------------- ### JavaScript Configuration as CLI String Source: https://github.com/cucumber/cucumber-js/blob/main/docs/configuration.md Configuration provided as a string of CLI-style options within a JavaScript file. Not recommended for complex configurations. ```js module.exports = { default: '--parallel 2 --format html:cucumber-report.html' } ``` -------------------------------- ### Plugin with Options and Options Key Source: https://github.com/cucumber/cucumber-js/blob/main/docs/plugins.md This JavaScript snippet shows how to define a plugin that receives options and uses `optionsKey` to target a specific part of the configuration object. ```javascript export default { type: 'plugin', coordinator: ({ options, on, logger }) => { on('message', (message) => { if (message.testRunFinished) { logger.info(options.bar) // yields `2` if the options are `{foo: {bar: 2}}` } }) }, optionsKey: 'foo' } ``` -------------------------------- ### Enabling Color Output with FORCE_COLOR Source: https://github.com/cucumber/cucumber-js/blob/main/docs/deprecations.md Demonstrates how to enable colored output using the FORCE_COLOR environment variable, replacing the deprecated `--format-options '{"colorsEnabled":true}'`. ```shell FORCE_COLOR=1 ``` -------------------------------- ### Run Unit Tests Source: https://github.com/cucumber/cucumber-js/blob/main/CONTRIBUTING.md Execute unit tests using Mocha, Chai, and Sinon for isolated component testing. ```bash npm run unit-test ``` -------------------------------- ### Configure Formatter Options in Configuration File Source: https://github.com/cucumber/cucumber-js/blob/main/docs/formatters.md Provide general configuration options for formatters using the 'formatOptions' key in a configuration file. Options are merged, with later ones taking precedence. ```javascript { formatOptions: { someOption: true } } ``` -------------------------------- ### Regular Expression Step Definition (Synchronous) Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/step_definitions.md Implements a step using a regular expression. Matching groups are passed as parameters. This is a synchronous example. ```javascript const { Then, When } = require('@cucumber/cucumber'); const assert = require('assert'); const fs = require('fs'); const seleniumWebdriver = require('selenium-webdriver'); // Synchronous Then(/^the response status is (.*)$/, function (status) { assert.equal(this.responseStatus, status) }); ``` -------------------------------- ### Specify Configuration File via CLI Source: https://github.com/cucumber/cucumber-js/blob/main/docs/configuration.md Use the --config option to specify a custom path for your configuration file. ```shell cucumber-js --config config/cucumber.json ``` -------------------------------- ### Enable Sharding via CLI Source: https://github.com/cucumber/cucumber-js/blob/main/docs/sharding.md Enable sharding directly from the command line using the `--shard` option. Specify the shard index and total number of shards in the `INDEX/TOTAL` format. ```bash cucumber-js --shard 1/3 ``` -------------------------------- ### Enable Rerun Formatter in Configuration File Source: https://github.com/cucumber/cucumber-js/blob/main/docs/rerun.md Enable the rerun formatter by specifying it in your Cucumber.js configuration file. The output file must start with '@'. ```javascript { format: ['rerun:@rerun.txt'] } ``` -------------------------------- ### Before Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/api_reference.md Defines a hook that runs before each scenario. It shares the same interface as `After` but executes in the defined order. ```APIDOC ## Before([options,] fn) ### Description Defines a hook which is run before each scenario. Multiple `Before` hooks are executed in the order that they are defined. Same interface as `After` except the first argument passed to `fn` will not have the `result` property. ### Parameters #### Path Parameters * `options` (object | string) - Optional - An object with `name`, `tags`, or `timeout` keys, or a string shorthand for `tags`. * `name` (string) - Optional - An optional name for this hook. * `tags` (string) - Optional - String tag expression used to apply this hook to only specific scenarios. * `timeout` (number) - Optional - A hook-specific timeout in milliseconds. * `fn` (function) - Required - The hook function. * The first argument is an object containing `{pickle, gherkinDocument, willBeRetried, testCaseStartedId}`. * For asynchronous callbacks, include a final argument for the callback function. ``` -------------------------------- ### Configure Formatter Options on the CLI Source: https://github.com/cucumber/cucumber-js/blob/main/docs/formatters.md Use the '--format-options' flag on the command line to pass formatter configuration as a JSON string. This option can be repeated. ```bash cucumber-js --format-options '{"someOption":true}' ``` -------------------------------- ### BeforeAll Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/api_reference.md Defines a hook that runs before all scenarios. It has the same interface as `AfterAll` and executes in the defined order. ```APIDOC ## BeforeAll([options,] fn) ### Description Defines a hook which is run before all scenarios. Multiple `BeforeAll` hooks are executed in the order that they are defined. Same interface as `AfterAll`. ### Parameters #### Path Parameters * `options` (object) - Optional - An object with `name` and `timeout` keys. * `name` (string) - Optional - An optional name for this hook. * `timeout` (number) - Optional - A hook-specific timeout in milliseconds. * `fn` (function) - Required - The hook function. * For asynchronous callbacks, have one argument for the callback function. ``` -------------------------------- ### BeforeStep Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/api_reference.md Defines a hook that runs before each step. Hooks are executed in the order they are defined. ```APIDOC ## BeforeStep([options,] fn) ### Description Defines a hook which is run before each step. Multiple `BeforeStep` hooks are executed in the order that they are defined. ### Parameters * `options` (object) - Optional. Configuration options for the hook. * `fn` (function) - The function to execute before each step. ``` -------------------------------- ### World Parameters in BeforeAll/AfterAll Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/hooks.md Shows how to access and update World parameters within BeforeAll/AfterAll hooks to drive automation or share context. Added in v10.1.0. ```javascript const {AfterAll, BeforeAll} = require('@cucumber/cucumber'); BeforeAll(async function () { this.parameters.accessToken = await getAccessToken(this.parameters.oauth) }); ``` -------------------------------- ### Example Rerun File Content Source: https://github.com/cucumber/cucumber-js/blob/main/docs/rerun.md A typical rerun file lists failing scenarios with their feature file and line numbers. This format is used by Cucumber.js to re-execute specific tests. ```gherkin features/adding.feature:3:19 features/editing.feature:8 ``` -------------------------------- ### Run Linter Source: https://github.com/cucumber/cucumber-js/blob/main/CONTRIBUTING.md Execute the linter to check for code style issues. ```bash npm run lint ``` -------------------------------- ### Register tsx for ESM Module Format Source: https://github.com/cucumber/cucumber-js/blob/main/docs/transpiling.md Create a registration file for ESM to enable tsx using its programmatic API. This setup is required before importing your TypeScript support code. ```javascript // tsx-register.js import { register } from 'tsx/esm/api' register() ``` -------------------------------- ### Formatter with Options Key Source: https://github.com/cucumber/cucumber-js/blob/main/docs/custom_formatters.md This formatter accesses specific options provided by the user via the 'optionsKey' configuration. It logs the value of 'options.bar' if it exists. ```javascript export default { type: 'formatter', formatter: ({ options, on, logger }) => { on('message', (message) => { if (message.testRunFinished) { logger.info(options.bar) // yields `2` if the options are `{foo: {bar: 2}}` } }) }, optionsKey: 'foo' } ``` -------------------------------- ### Skipping Scenario in Before Hook Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/hooks.md Demonstrates how to imperatively skip a scenario from within a Before hook using synchronous return. ```javascript // Synchronous Before(function() { // perform some runtime check to decide whether to skip the proceeding scenario return 'skipped' }); ``` -------------------------------- ### Then Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/api_reference.md Defines a 'Then' step that matches a Gherkin step pattern. Has the same interface as `Given`. ```APIDOC ## Then(pattern[, options], fn) ### Description Define a "Then" step. Same interface as `Given`. ### Parameters * `pattern` (regex|string) - A regex or string pattern to match against a gherkin step. * `options` (object) - Optional. An object with configuration options. * `fn` (function) - The function to execute for this step. ``` -------------------------------- ### Invoke Profile using Short Flag Source: https://github.com/cucumber/cucumber-js/blob/main/docs/profiles.md The -p flag is a shorthand for the --profile option to activate a specific configuration set. ```shell cucumber-js -p my_profile ``` -------------------------------- ### Preload Support Code with loadSupport Source: https://github.com/cucumber/cucumber-js/blob/main/docs/javascript_api.md Use `loadSupport` to load the support code library once upfront. Pass the loaded support code into `runCucumber` for multiple test runs. ```javascript import { loadConfiguration, loadSupport, runCucumber } from '@cucumber/cucumber/api' const { runConfiguration } = await loadConfiguration() const support = await loadSupport(runConfiguration) const result1 = await runCucumber({ ...runConfiguration, support }) const result2 = await runCucumber({ ...runConfiguration, support }) const result3 = await runCucumber({ ...runConfiguration, support }) ``` -------------------------------- ### Helper for Tag-Based Parallel Assignment Source: https://github.com/cucumber/cucumber-js/blob/main/docs/parallel.md Use helper functions from `@cucumber/cucumber` to define rules for parallel assignment based on tags. This example restricts parallel execution to at most one pickle per specified tag. ```javascript import { setParallelCanAssign, parallelCanAssignHelpers, } from '@cucumber/cucumber' const { atMostOnePicklePerTag } = parallelCanAssignHelpers const myTagRule = atMostOnePicklePerTag(['@tag1', '@tag2']) // Only one pickle with @tag1 can run at a time // AND only one pickle with @tag2 can run at a time setParallelCanAssign(myTagRule) // If you want to join a tag rule with other rules you can compose them like so: const myCustomRule = function (pickleInQuestion, picklesInProgress) { // ... } setParallelCanAssign(function (pickleInQuestion, picklesInProgress) { return ( myCustomRule(pickleInQuestion, picklesInProgress) && myTagRule(pickleInQuestion, picklesInProgress) ) }) ``` -------------------------------- ### Default Profile Configuration Source: https://github.com/cucumber/cucumber-js/blob/main/docs/profiles.md Defines the default configuration for local development, including formatters, module loading, and world parameters. ```javascript module.exports = { default: { format: ['progress-bar', 'html:cucumber-report.html'], requireModule: ['tsx/cjs'], require: ['support/**/*.ts'], worldParameters: { appUrl: 'http://localhost:3000/' } } } ``` -------------------------------- ### Profile Configuration for World Parameters Source: https://github.com/cucumber/cucumber-js/blob/main/docs/profiles.md Uses profiles to pass complex JSON arguments to worldParameters, aliasing different device and browser configurations. ```javascript module.exports = { desktop: `--world-parameters '{"device": {"type":"desktop","height":720,"width":1280}}'`, phone: `--world-parameters '{"device": {"type":"phone","height":568,"width":320}}'`, tablet: `--world-parameters '{"device": {"type":"tablet","height":1024,"width":768}}'`, chromium: `--world-parameters '{"browser": "chromium"}'`, firefox: `--world-parameters '{"browser": "firefox"}'`, webkit: `--world-parameters '{"browser": "webkit"}'` } ``` -------------------------------- ### CoordinatorContext Source: https://github.com/cucumber/cucumber-js/blob/main/exports/api/report.api.md Provides context for coordinator plugins, including event handling, transformation capabilities, options, logger, and environment details. ```APIDOC ## Type: CoordinatorContext ### Description Provides context for coordinator plugins, including event handling, transformation capabilities, options, logger, and environment details. ### Type Parameters * `OptionsType`: The type of the options object for the plugin. ### Properties * `operation`: The current plugin operation. * `on`: A function to register event handlers for specific coordinator events. * `transform`: A function to register transformation handlers for specific coordinator events. * `options`: The options provided to the plugin. * `logger`: An instance of ILogger for logging. * `environment`: Details about the coordinator's environment. ``` -------------------------------- ### When Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/api_reference.md Defines a 'When' step that matches a Gherkin step pattern. Has the same interface as `Given`. ```APIDOC ## When(pattern[, options], fn) ### Description Define a "When" step. Same interface as `Given`. ### Parameters * `pattern` (regex|string) - A regex or string pattern to match against a gherkin step. * `options` (object) - Optional. An object with configuration options. * `fn` (function) - The function to execute for this step. ``` -------------------------------- ### ILoadConfigurationOptions Source: https://github.com/cucumber/cucumber-js/blob/main/exports/api/report.api.md Options for loading Cucumber.js configuration. ```APIDOC ## Interface: ILoadConfigurationOptions ### Description Options for loading Cucumber.js configuration. ### Properties * `file`: The path to the configuration file, or `false` to disable. * `profiles`: An array of profile names to load. * `provided`: Partial configuration object, an array of strings, or a single string. ``` -------------------------------- ### Specify Formatters in Configuration File Source: https://github.com/cucumber/cucumber-js/blob/main/docs/formatters.md Configure one or more formatters using the 'format' option in a configuration file. For formatters that write to a file, provide the format name and the output path as an array. ```javascript { format: ['progress-bar', ['html', 'cucumber-report.html']] } ``` -------------------------------- ### After Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/api_reference.md Defines a hook that runs after each scenario. It can be configured with options like tags and timeouts. ```APIDOC ## After([options,] fn) ### Description Defines a hook which is run after each scenario. Multiple `After` hooks are executed in the reverse order that they are defined. ### Parameters #### Path Parameters * `options` (object | string) - Optional - An object with `name`, `tags`, or `timeout` keys, or a string shorthand for `tags`. * `name` (string) - Optional - An optional name for this hook. * `tags` (string) - Optional - String tag expression used to apply this hook to only specific scenarios. * `timeout` (number) - Optional - A hook-specific timeout in milliseconds. * `fn` (function) - Required - The hook function. * The first argument is an object containing `{pickle, gherkinDocument, result, error, willBeRetried, testCaseStartedId}`. * For asynchronous callbacks, include a final argument for the callback function. ``` -------------------------------- ### Combine Multiple Profiles for World Parameters Source: https://github.com/cucumber/cucumber-js/blob/main/docs/profiles.md Demonstrates invoking Cucumber.js with multiple profiles ('webkit' and 'phone') to merge their world parameters for a specific test run. ```shell cucumber-js -p webkit -p phone ``` -------------------------------- ### ILoadSupportOptions Source: https://github.com/cucumber/cucumber-js/blob/main/exports/api/report.api.md Options for loading support code, including source coordinates and support code coordinates. ```APIDOC ## Interface: ILoadSupportOptions ### Description Options for loading support code, including source coordinates and support code coordinates. ### Properties * `sources`: Source coordinates for loading. * `support`: Partial support code coordinates. ``` -------------------------------- ### Attach Binary Data from Stream (Callback) Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/attachments.md Attach binary data from a stream using a callback. Ensure the callback is invoked after attaching. ```javascript var {After, Status} = require('@cucumber/cucumber'); // Passing a callback After(function (testCase, callback) { if (testCase.result.status === Status.FAILED) { var stream = getScreenshotOfError(); this.attach(stream, { mediaType: 'image/png' }, callback); } else { callback(); } }); ``` -------------------------------- ### ESM Default and CI Profiles Source: https://github.com/cucumber/cucumber-js/blob/main/docs/profiles.md Configuration using ES Modules syntax, exporting the default profile and a named 'ci' profile. ```javascript const common = { requireModule: ['ts-node/register'], require: ['support/**/*.ts'], worldParameters: { appUrl: process.env.MY_APP_URL || 'http://localhost:3000/' } } export default { ...common, format: ['progress-bar', 'html:cucumber-report.html'], } export const ci = { ...common, format: ['html:cucumber-report.html'], publish: true } ``` -------------------------------- ### Run Compatibility Kit Tests Source: https://github.com/cucumber/cucumber-js/blob/main/CONTRIBUTING.md Verify that cucumber-js emits the correct messages according to the compatibility kit. ```bash npm run cck-test ``` -------------------------------- ### IRunConfiguration Source: https://github.com/cucumber/cucumber-js/blob/main/exports/api/report.api.md Represents the configuration for running Cucumber.js. ```APIDOC ## Interface: IRunConfiguration ### Description Represents the configuration for running Cucumber.js. ### Properties (Undocumented in the source) ``` -------------------------------- ### Configure Specific Formatter Options on CLI Source: https://github.com/cucumber/cucumber-js/blob/main/docs/formatters.md Pass specific formatter options on the command line by nesting them within the JSON string provided to '--format-options'. ```bash cucumber-js --format-options '{"pretty":{"useStatusIcon":false}}' ``` -------------------------------- ### Override Support Code Paths in Configuration Source: https://github.com/cucumber/cucumber-js/blob/main/docs/configuration.md Use the 'import' option in the configuration file to specify custom paths for support code files. This replaces the default logic. ```javascript { import: ['somewhere-else/support/*.js'] } ``` -------------------------------- ### Test Run Hooks (AfterAll, BeforeAll) Source: https://github.com/cucumber/cucumber-js/blob/main/exports/root/report.api.md Defines functions that can be executed once after or before the entire test run. These hooks can be configured with options. ```APIDOC ## AfterAll ### Description Executes a function once after the test run is completed. ### Method Signature `AfterAll(code: TestRunHookFunction)` `AfterAll(options: IDefineTestRunHookOptions, code: TestRunHookFunction)` ### Parameters - **code** (TestRunHookFunction) - The function to execute after the test run. - **options** (IDefineTestRunHookOptions) - Options to configure the hook. ## BeforeAll ### Description Executes a function once before the test run begins. ### Method Signature `BeforeAll(code: TestRunHookFunction)` `BeforeAll(options: IDefineTestRunHookOptions, code: TestRunHookFunction)` ### Parameters - **code** (TestRunHookFunction) - The function to execute before the test run. - **options** (IDefineTestRunHookOptions) - Options to configure the hook. ``` -------------------------------- ### FormatterBuilder Source: https://github.com/cucumber/cucumber-js/blob/main/exports/root/report.api.md Provides methods for building and loading formatters, as well as obtaining step definition snippet builders. ```APIDOC ## FormatterBuilder ### Description Provides static methods for creating and managing formatters and related utilities. ### Methods - **build(FormatterConstructor: string | typeof Formatter, options: IBuildOptions): Promise** Builds a formatter instance. - **getConstructorByType(type: string, cwd: string): Promise** Retrieves a formatter constructor by its type. - **getStepDefinitionSnippetBuilder(input: IGetStepDefinitionSnippetBuilderOptions): Promise** Gets a StepDefinitionSnippetBuilder instance. - **loadCustomClass(type: "formatter" | "syntax", descriptor: string, cwd: string): Promise** Loads a custom formatter or syntax class. - **loadFile(urlOrName: URL | string): Promise** Loads a file, potentially containing custom code. - **resolveConstructor(ImportedCode: any): any** Resolves a constructor from imported code. ``` -------------------------------- ### IPickleOrder Source: https://github.com/cucumber/cucumber-js/blob/main/exports/api/report.api.md Defines the possible orders for running pickles. ```APIDOC ## Type: IPickleOrder ### Description Defines the possible orders for running pickles. ### Possible Values * `'defined'` * `'reverse'` * `'random'` * `random:`: Random order with a specific seed. ``` -------------------------------- ### Step Hooks (AfterStep, BeforeStep) Source: https://github.com/cucumber/cucumber-js/blob/main/exports/root/report.api.md Defines functions that can be executed after or before individual test steps. These hooks can be tagged or configured with options. ```APIDOC ## AfterStep ### Description Executes a function after a test step. ### Method Signature `AfterStep(code: TestStepHookFunction)` `AfterStep(tags: string, code: TestStepHookFunction)` `AfterStep(options: IDefineTestStepHookOptions, code: TestStepHookFunction)` ### Parameters - **code** (TestStepHookFunction) - The function to execute after the test step. - **tags** (string) - Optional tags to filter which test steps trigger this hook. - **options** (IDefineTestStepHookOptions) - Options to configure the hook. ## BeforeStep ### Description Executes a function before a test step. ### Method Signature `BeforeStep(code: TestStepHookFunction)` `BeforeStep(tags: string, code: TestStepHookFunction)` `BeforeStep(options: IDefineTestStepHookOptions, code: TestStepHookFunction)` ### Parameters - **code** (TestStepHookFunction) - The function to execute before the test step. - **tags** (string) - Optional tags to filter which test steps trigger this hook. - **options** (IDefineTestStepHookOptions) - Options to configure the hook. ``` -------------------------------- ### Tagged Hooks Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/hooks.md Illustrates how to conditionally execute hooks based on scenario tags using various tag expression combinations. ```javascript const {After, Before} = require('@cucumber/cucumber'); Before(function () { // This hook will be executed before all scenarios }); Before({tags: "@foo"}, function () { // This hook will be executed before scenarios tagged with @foo }); Before({tags: "@foo and @bar"}, function () { // This hook will be executed before scenarios tagged with @foo and @bar }); Before({tags: "@foo or @bar"}, function () { // This hook will be executed before scenarios tagged with @foo or @bar }); // You can use the following shorthand when only specifying tags Before("@foo", function () { // This hook will be executed before scenarios tagged with @foo }); ``` -------------------------------- ### loadSupport Source: https://github.com/cucumber/cucumber-js/blob/main/exports/api/report.api.md Loads the support code (e.g., step definitions, hooks) based on the provided options and environment. This function prepares the necessary code for cucumber to execute features. ```APIDOC ## loadSupport ### Description Loads the support code (e.g., step definitions, hooks) based on the provided options and environment. This function prepares the necessary code for cucumber to execute features. ### Function Signature `loadSupport(options: ILoadSupportOptions, environment?: IRunEnvironment): Promise` ### Parameters #### options - **options** (ILoadSupportOptions) - Required - Options for loading support code. #### environment - **environment** (IRunEnvironment) - Optional - The runtime environment. ### Returns - **Promise** - A promise that resolves with the loaded support code library. ``` -------------------------------- ### Attach Text with Filename Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/attachments.md Attach text content with a specified MIME type and a filename for potential download. ```javascript var {After} = require('@cucumber/cucumber'); After(function () { this.attach('{"name": "some JSON"}', { mediaType: 'application/json', fileName: 'results.json' }); }); ``` -------------------------------- ### Specify Formatters on the CLI Source: https://github.com/cucumber/cucumber-js/blob/main/docs/formatters.md Use the '--format' option on the command line to specify formatters. For formatters that write to a file, use a colon delimiter and quote each part. ```bash cucumber-js --format progress-bar --format "html":"cucumber-report.html" ``` -------------------------------- ### Filter Scenarios by Feature File Path Source: https://github.com/cucumber/cucumber-js/blob/main/docs/filtering.md Specify an individual feature file to run using the 'paths' option in a configuration file or on the CLI. ```javascript { paths: ['features/my_feature.feature'] } ``` ```bash cucumber-js features/my_feature.feature ``` -------------------------------- ### Enable Rerun Formatter via CLI Source: https://github.com/cucumber/cucumber-js/blob/main/docs/rerun.md Enable the rerun formatter directly from the command line. The output file name must begin with '@'. ```bash cucumber-js --format rerun:@rerun.txt ``` -------------------------------- ### Attach Binary Data from Buffer Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/attachments.md Attach binary data directly from a Buffer object, such as a screenshot. ```javascript var {After, Status} = require('@cucumber/cucumber'); After(function (testCase) { if (testCase.result.status === Status.FAILED) { var buffer = getScreenshotOfError(); this.attach(buffer, { mediaType: 'image/png' }); } }); ``` -------------------------------- ### loadConfiguration Source: https://github.com/cucumber/cucumber-js/blob/main/exports/api/report.api.md Loads the cucumber configuration based on provided options and environment. This function is essential for setting up the cucumber runtime with specific configurations. ```APIDOC ## loadConfiguration ### Description Loads the cucumber configuration based on provided options and environment. This function is essential for setting up the cucumber runtime with specific configurations. ### Function Signature `loadConfiguration(options?: ILoadConfigurationOptions, environment?: IRunEnvironment): Promise` ### Parameters #### options - **options** (ILoadConfigurationOptions) - Optional - Configuration options for loading. #### environment - **environment** (IRunEnvironment) - Optional - The runtime environment. ### Returns - **Promise** - A promise that resolves with the resolved configuration. ``` -------------------------------- ### Given Source: https://github.com/cucumber/cucumber-js/blob/main/docs/support_files/api_reference.md Defines a 'Given' step that matches a Gherkin step pattern. Aliases: `defineStep`. ```APIDOC ## Given(pattern[, options], fn) ### Description Define a "Given" step. This function is used to map Gherkin steps to JavaScript functions. ### Parameters * `pattern` (regex|string) - A regex or string pattern to match against a gherkin step. * `options` (object) - Optional. An object with the following keys: - `timeout` (number): A step-specific timeout, to override the default timeout. - `wrapperOptions` (object): Step-specific options that are passed to the definition function wrapper. * `fn` (function) - A function, which should be defined as follows: - Should have one argument for each capture in the regular expression. - May have an additional argument if the gherkin step has a docstring or data table. - When using the asynchronous callback interface, have one final argument for the callback function. ``` -------------------------------- ### Enable Parallel Execution Source: https://github.com/cucumber/cucumber-js/blob/main/docs/parallel.md Configure the number of parallel workers using the `parallel` option in a configuration file or via the CLI. ```json { "parallel": 3 } ``` ```bash cucumber-js --parallel 3 ``` -------------------------------- ### CoordinatorEnvironment Source: https://github.com/cucumber/cucumber-js/blob/main/exports/api/report.api.md Defines the environment in which the coordinator operates, including the current working directory, standard error stream, and environment variables. ```APIDOC ## Type: CoordinatorEnvironment ### Description Defines the environment in which the coordinator operates, including the current working directory, standard error stream, and environment variables. ### Properties * `cwd`: The current working directory. * `stderr`: A writable stream for standard error. * `env`: An object containing environment variables. ``` -------------------------------- ### Configure Retry on the CLI Source: https://github.com/cucumber/cucumber-js/blob/main/docs/retry.md Enable the retry functionality by specifying the number of retries on the command line interface. This is an alternative to using a configuration file. ```bash cucumber-js --retry 1 ```