The official JavaScript implementation of Cucumber, a behavior-driven development testing framework for writing tests in plain language.
npx @tessl/cli install tessl/npm-cucumber--cucumber@12.2.0Cucumber.js is the official JavaScript implementation of Cucumber, a behavior-driven development (BDD) testing framework that enables automated tests to be written in plain language using the Gherkin syntax. This comprehensive testing library allows teams to write feature specifications in natural language that can be understood by both technical and non-technical stakeholders, promoting better communication and collaboration.
npm install @cucumber/cucumberimport {
Given, When, Then, Before, After, BeforeAll, AfterAll, BeforeStep, AfterStep,
DataTable, World, defineStep, defineParameterType, setDefaultTimeout,
setWorldConstructor, setDefinitionFunctionWrapper, setParallelCanAssign,
Formatter, FormatterBuilder, JsonFormatter, ProgressFormatter, RerunFormatter,
SnippetsFormatter, SummaryFormatter, UsageFormatter, UsageJsonFormatter,
formatterHelpers, parallelCanAssignHelpers, supportCodeLibraryBuilder,
wrapPromiseWithTimeout, TestCaseHookDefinition,
Status, version, world, context
} from "@cucumber/cucumber";For CommonJS:
const {
Given, When, Then, Before, After, BeforeAll, AfterAll, BeforeStep, AfterStep,
DataTable, World, defineStep, defineParameterType, setDefaultTimeout,
setWorldConstructor, setDefinitionFunctionWrapper, setParallelCanAssign,
Formatter, FormatterBuilder, JsonFormatter, ProgressFormatter, RerunFormatter,
SnippetsFormatter, SummaryFormatter, UsageFormatter, UsageJsonFormatter,
formatterHelpers, parallelCanAssignHelpers, supportCodeLibraryBuilder,
wrapPromiseWithTimeout, TestCaseHookDefinition,
Status, version, world, context
} = require("@cucumber/cucumber");For programmatic API usage:
import {
runCucumber, loadConfiguration, loadSources, loadSupport,
IRunOptions, IRunResult, ILoadConfigurationOptions, IResolvedConfiguration,
ILoadSourcesResult, ILoadSupportOptions, ISupportCodeLibrary
} from "@cucumber/cucumber/api";import { Given, When, Then, Before, After, DataTable } from "@cucumber/cucumber";
// Step definitions
Given('I have {int} cucumbers', function (count: number) {
this.cucumberCount = count;
});
When('I eat {int} cucumbers', function (count: number) {
this.cucumberCount -= count;
});
Then('I should have {int} cucumbers', function (expected: number) {
if (this.cucumberCount !== expected) {
throw new Error(`Expected ${expected}, but got ${this.cucumberCount}`);
}
});
// Hooks
Before(function () {
this.cucumberCount = 0;
});
After(function () {
// Cleanup after each test
});Cucumber.js is built around several key components:
Core functions for defining test steps that match Gherkin language patterns and execute corresponding JavaScript code.
function Given<WorldType = IWorld>(pattern: string | RegExp, code: TestStepFunction<WorldType>): void;
function Given<WorldType = IWorld>(pattern: string | RegExp, options: IDefineStepOptions, code: TestStepFunction<WorldType>): void;
function When<WorldType = IWorld>(pattern: string | RegExp, code: TestStepFunction<WorldType>): void;
function When<WorldType = IWorld>(pattern: string | RegExp, options: IDefineStepOptions, code: TestStepFunction<WorldType>): void;
function Then<WorldType = IWorld>(pattern: string | RegExp, code: TestStepFunction<WorldType>): void;
function Then<WorldType = IWorld>(pattern: string | RegExp, options: IDefineStepOptions, code: TestStepFunction<WorldType>): void;
function defineStep<WorldType = IWorld>(pattern: string | RegExp, code: TestStepFunction<WorldType>): void;
function defineStep<WorldType = IWorld>(pattern: string | RegExp, options: IDefineStepOptions, code: TestStepFunction<WorldType>): void;Lifecycle hooks for test setup and teardown at scenario, step, and suite levels with support for conditional execution.
function Before<WorldType = IWorld>(code: TestCaseHookFunction<WorldType>): void;
function Before<WorldType = IWorld>(tags: string, code: TestCaseHookFunction<WorldType>): void;
function Before<WorldType = IWorld>(options: IDefineTestCaseHookOptions, code: TestCaseHookFunction<WorldType>): void;
function After<WorldType = IWorld>(code: TestCaseHookFunction<WorldType>): void;
function After<WorldType = IWorld>(tags: string, code: TestCaseHookFunction<WorldType>): void;
function After<WorldType = IWorld>(options: IDefineTestCaseHookOptions, code: TestCaseHookFunction<WorldType>): void;
function BeforeAll(code: TestRunHookFunction): void;
function AfterAll(code: TestRunHookFunction): void;
function BeforeStep<WorldType = IWorld>(code: TestStepHookFunction<WorldType>): void;
function AfterStep<WorldType = IWorld>(code: TestStepHookFunction<WorldType>): void;Test context management system providing state sharing between steps and access to test metadata.
class World<ParametersType = any> implements IWorld<ParametersType> {
constructor({ attach, log, link, parameters }: IWorldOptions<ParametersType>);
readonly attach: ICreateAttachment;
readonly log: ICreateLog;
readonly link: ICreateLink;
readonly parameters: ParametersType;
}
interface IWorld<ParametersType = any> {
readonly attach: ICreateAttachment;
readonly log: ICreateLog;
readonly link: ICreateLink;
readonly parameters: ParametersType;
[key: string]: any;
}
interface IWorldOptions<ParametersType = any> {
attach: ICreateAttachment;
log: ICreateLog;
link: ICreateLink;
parameters: ParametersType;
}
const world: IWorld;
const context: IContext;Utilities for working with structured test data including Gherkin data tables and parameter types.
class DataTable {
constructor(sourceTable: messages.PickleTable | string[][]);
hashes(): Record<string, string>[];
raw(): string[][];
rows(): string[][];
rowsHash(): Record<string, string>;
transpose(): DataTable;
}
function defineParameterType<T>(options: IParameterTypeDefinition<T>): void;Extensible output formatting system for generating test reports in various formats including JSON, HTML, and custom formats.
abstract class Formatter {
constructor(options: IFormatterOptions);
abstract handleMessage(message: Envelope): void;
}
class JsonFormatter extends Formatter;
class ProgressFormatter extends Formatter;
class SummaryFormatter extends Formatter;
class UsageFormatter extends Formatter;Functions for running Cucumber tests programmatically, loading configurations, and integrating with build tools and IDEs.
function runCucumber(
options: IRunOptions,
environment?: IRunEnvironment,
onMessage?: (message: Envelope) => void
): Promise<IRunResult>;
function loadConfiguration(
options?: ILoadConfigurationOptions,
environment?: IRunEnvironment
): Promise<IResolvedConfiguration>;
function loadSources(
coordinates: ISourcesCoordinates,
environment?: IRunEnvironment
): Promise<ILoadSourcesResult>;
function loadSupport(
options: ILoadSupportOptions,
environment?: IRunEnvironment
): Promise<ISupportCodeLibrary>;Utilities for controlling parallel test execution and assignment validation.
function atMostOnePicklePerTag(tagNames: string[]): ParallelAssignmentValidator;
interface ParallelAssignmentValidator {
(inQuestion: messages.Pickle, inProgress: messages.Pickle[]): boolean;
}
const parallelCanAssignHelpers: {
atMostOnePicklePerTag: typeof atMostOnePicklePerTag;
};Promise timeout wrapper and time-related helper functions.
function wrapPromiseWithTimeout<T>(
promise: Promise<T>,
timeoutInMilliseconds: number,
timeoutMessage?: string
): Promise<T>;Core support code library construction and management.
const supportCodeLibraryBuilder: {
methods: {
After: typeof After;
AfterAll: typeof AfterAll;
AfterStep: typeof AfterStep;
Before: typeof Before;
BeforeAll: typeof BeforeAll;
BeforeStep: typeof BeforeStep;
defineStep: typeof defineStep;
defineParameterType: typeof defineParameterType;
Given: typeof Given;
setDefaultTimeout: typeof setDefaultTimeout;
setDefinitionFunctionWrapper: typeof setDefinitionFunctionWrapper;
setWorldConstructor: typeof setWorldConstructor;
setParallelCanAssign: typeof setParallelCanAssign;
Then: typeof Then;
When: typeof When;
};
};Collection of utilities for custom formatter development.
const formatterHelpers: {
EventDataCollector: typeof EventDataCollector;
parseTestCaseAttempt: (messages: Envelope[]) => TestCaseAttempt;
formatLocation: (location: Location) => string;
formatSummary: (summary: TestSummary) => string;
formatDuration: (duration: Duration) => string;
formatIssue: (issue: TestIssue) => string;
};Configuration system supporting profiles, CLI options, and programmatic settings for customizing test execution behavior.
interface IConfiguration {
paths?: string[];
backtrace?: boolean;
dryRun?: boolean;
failFast?: boolean;
format?: string[];
formatOptions?: { [key: string]: any };
parallel?: number;
profiles?: IProfiles;
require?: string[];
requireModule?: string[];
tags?: string;
worldParameters?: { [key: string]: any };
}
interface IProfiles {
[profileName: string]: Partial<IConfiguration>;
}const Status: typeof messages.TestStepResultStatus;
const version: string;
class TestCaseHookDefinition;type TestStepFunction<WorldType> = (this: WorldType, ...args: any[]) => any | Promise<any>;
type TestCaseHookFunction<WorldType> = (this: WorldType, arg: ITestCaseHookParameter) => any | Promise<any>;
type TestStepHookFunction<WorldType> = (this: WorldType, arg: ITestStepHookParameter) => any | Promise<any>;
type TestRunHookFunction = (this: { parameters: JsonObject }) => any | Promise<any>;
interface IDefineStepOptions {
timeout?: number;
wrapperOptions?: any;
}
interface IDefineTestCaseHookOptions {
name?: string;
tags?: string;
timeout?: number;
}
interface ITestCaseHookParameter {
gherkinDocument: messages.GherkinDocument;
pickle: messages.Pickle;
result?: messages.TestStepResult;
error?: any;
willBeRetried?: boolean;
testCaseStartedId: string;
}
interface ITestStepHookParameter {
gherkinDocument: messages.GherkinDocument;
pickle: messages.Pickle;
pickleStep: messages.PickleStep;
result: messages.TestStepResult;
error?: any;
testCaseStartedId: string;
testStepId: string;
}
interface IParameterTypeDefinition<T> {
name: string;
regexp: readonly RegExp[] | readonly string[] | RegExp | string;
transformer?: (...match: string[]) => T;
useForSnippets?: boolean;
preferForRegexpMatch?: boolean;
}