ScreenshotNeo

BlogHow-to

How to Fix Missing Cucumber Step Definitions in Cypress

Fix Cypress Cucumber “undefined” steps by checking expression matching, file pairing, configuration precedence, package versions, and bundler errors.

By the ScreenshotNeo team30 September 20267 min read

How to Fix Missing Cucumber Step Definitions in Cypress

Quick answer: Cypress reports a Cucumber step as undefined when no registered step definition matches the text after Given, When, Then, And, or But. Check the expression first, then verify that the step-definition file is discovered and paired with the feature, that the maintained package is installed and imported, and that a bundler error is not being mistaken for a matching error.

Cucumber marks an unmatched step undefined and skips the remaining steps in that scenario. A step definition is a method whose expression links it to one or more Gherkin steps (Cucumber step-definition documentation).

1. Copy the exact undefined step

Start with the Cypress output and the .feature file. Compare only the text after the keyword. The registration function name does not determine matching: a definition registered with Given can match a step written with When if the expression text matches.

Feature: Account access

  Scenario: Sign in
    Given I log in as "admin"

The text to match is I log in as "admin", not Given I log in as "admin".

2. Fix the expression and parameters

Definitions can use a Cucumber Expression or a regular expression. Literal words, punctuation, anchors, capture groups, and parameter types must agree with the feature text.

import { Given } from '@badeball/cypress-cucumber-preprocessor';

Given('I log in as {string}', (role) => {
  cy.visit('/login');
  cy.get('[name="role"]').select(role);
});

This matches Given I log in as "admin". If the feature says I log in as admin without quotes, change the feature or use an expression or regular expression that accepts the intended syntax. Confirm parameter syntax against the version of the Cucumber expression implementation installed in your project.

Common matching mistakes

  • Different punctuation: I submit the form. and I submit the form are different literal expressions.
  • Different whitespace or wording: “the account” and “an account” do not match a literal expression.
  • Quoted versus unquoted values: {string} is intended for quoted Cucumber values.
  • Regular-expression anchors: ^I log in as (.*)$ will not match extra text after the final character.
  • Duplicate definitions: two expressions can create an ambiguous match after the file becomes visible. Remove or narrow one.

3. Put step files where the preprocessor can discover them

The maintained preprocessor uses stepDefinitions glob patterns to decide which files are available to each feature. A correct definition outside those patterns is invisible. Pairing determines which definitions are available to which feature (pairing documentation).

Cucumber must match the step expression and discover the file through the configured pairing pattern.
Cucumber must match the step expression and discover the file through the configured pairing pattern.

For a feature at cypress/e2e/duckduckgo.feature, these documented layouts are typical:

cypress/e2e/duckduckgo.feature
cypress/e2e/duckduckgo/steps.ts

# or
cypress/e2e/duckduckgo.feature
cypress/e2e/duckduckgo.ts

# or shared definitions
cypress/e2e/duckduckgo.feature
cypress/support/step_definitions/duckduckgo.ts

Use deliberate patterns. A broad cypress/e2e/**/*.js glob exposes every definition and hook to every feature, which can cause duplicate or ambiguous matches.

4. Configure pairing in one authoritative location

With a dedicated .cypress-cucumber-preprocessorrc.json, put the settings there. With package.json, nest them under cypress-cucumber-preprocessor:

{
  "cypress-cucumber-preprocessor": {
    "stepDefinitions": [
      "cypress/e2e/[filepath]/**/*.{js,ts}",
      "cypress/e2e/[filepath].{js,ts}",
      "cypress/support/step_definitions/**/*.{js,ts}"
    ]
  }
}

The [filepath] token lets definitions beside a feature be paired with that feature. If your features use another common root, derive the prefix from that root and add an explicit shared-directory glob when needed.

Do not leave an empty or conflicting cypress-cucumber-preprocessor block in package.json while expecting a separate configuration file to win. Only one configuration location applies. When uncertain, inspect the debug output (preprocessor FAQ and configuration guidance):

DEBUG=cypress:electron,cypress-cucumber-preprocessor npx cypress run

5. Use one package lineage and matching imports

Do not mix the old unscoped package with the maintained scoped package. The current maintainer FAQ describes cypress-cucumber-preprocessor as severely outdated and recommends using @badeball/cypress-cucumber-preprocessor consistently.

npm ls @badeball/cypress-cucumber-preprocessor cypress-cucumber-preprocessor

Inspect package.json, the lockfile, and every step file. A consistent setup looks like this:

npm install --save-dev @badeball/cypress-cucumber-preprocessor

import { Given, When, Then } from '@badeball/cypress-cucumber-preprocessor';

Remove stale imports and duplicate package entries before diagnosing matching.

6. Separate undefined matching from preprocessing and bundling

If Cypress shows an undefined step, follow the matching and pairing checks above. If it shows a webpack or esbuild compilation error, the definition may already have been found and the failure is in preprocessing or bundling. Cypress documents that Cucumber uses a third-party bundler; with esbuild, configure inline source maps so code frames remain useful (Cypress preprocessor documentation).

// cypress.config.ts (illustrative bundler wiring)
import { defineConfig } from 'cypress';
import createBundler from '@bahmutov/cypress-esbuild-preprocessor';

export default defineConfig({
  e2e: {
    setupNodeEvents(on) {
      on('file:preprocessor', createBundler({
        sourcemap: 'inline'
      }));
    }
  }
});

Use the bundler configuration required by your installed preprocessor version. Fix syntax, TypeScript, alias, and source-map errors separately from step-expression errors.

7. A repeatable diagnostic workflow

  1. Copy the exact undefined text after the Gherkin keyword.
  2. Find the registration and compare every literal character, parameter type, quote, and regular-expression anchor.
  3. Confirm the file extension is included by the configured glob.
  4. Confirm the feature path and the step-definition path satisfy the intended pairing pattern.
  5. Run with DEBUG=cypress:electron,cypress-cucumber-preprocessor and verify the active configuration and discovered files.
  6. Check that only @badeball/cypress-cucumber-preprocessor (or the package lineage required by your project version) is installed and imported.
  7. If the message is a compiler error, debug the bundler before changing expressions.
  8. After the step is found, watch for a new error: duplicate definitions produce ambiguity, while a failing command inside the definition is an implementation failure.

8. Minimal working example

These files demonstrate a feature-local definition.

# cypress/e2e/login.feature
Feature: Login
  Scenario: Admin login
    Given I log in as "admin"
    Then I should see the dashboard
// cypress/e2e/login/steps.ts
import { Given, Then } from '@badeball/cypress-cucumber-preprocessor';

Given('I log in as {string}', (role) => {
  cy.visit('/login');
  cy.get('[name="role"]').select(role);
  cy.get('button[type="submit"]').click();
});

Then('I should see the dashboard', () => {
  cy.get('[data-testid="dashboard"]').should('be.visible');
});
// cypress.config.ts
import { defineConfig } from 'cypress';
import preprocessor from '@badeball/cypress-cucumber-preprocessor';

export default defineConfig({
  e2e: {
    specPattern: 'cypress/e2e/**/*.feature',
    async setupNodeEvents(on, config) {
      await preprocessor.addCucumberPreprocessorPlugin(on, config);
      return config;
    }
  }
});

The exact plugin and bundler wiring can vary by installed release. Keep the package documentation version aligned with your lockfile.

9. Troubleshooting table

Symptom Likely cause Fix
Every step is undefined No step files are paired, or the plugin is not registered Check setupNodeEvents, globs, feature root, and debug output.
One step is undefined Expression text or parameter syntax differs Compare text after the keyword character by character.
Definitions work in one feature only Feature-local pairing is intentional or a shared glob is missing Add a narrowly scoped shared-directory pattern.
“Undefined” changes to “ambiguous” Multiple discovered expressions match Delete duplicates or make expressions more specific.
Cannot resolve package/import Old and maintained packages are mixed, or dependency is absent Use one package family and reinstall from the lockfile.
Webpack/esbuild compilation error Bundler or source-map configuration Fix preprocessing separately; enable inline source maps for esbuild.
JavaScript file is ignored Glob includes only TypeScript or uses the wrong directory Include {js,ts} and verify the relative path.
Step runs but assertion fails Matching succeeded; implementation or application state is wrong Debug the Cypress commands and page state.

10. Performance, reliability, and maintenance

  • Keep feature-local definitions local when steps are specific; use a shared directory only for stable, reusable behavior.
  • Prefer precise expressions over catch-all regular expressions. They reduce ambiguity and make refactors visible.
  • Keep one configuration source and commit the lockfile so package and syntax changes are reviewable.
  • Use debug logging only while diagnosing; remove noisy CI settings after confirming pairing.
  • When upgrading, recheck the maintained preprocessor documentation because configuration syntax and bundler integrations can change with releases.
  • Separate failures into layers: discovery, expression matching, preprocessing, then Cypress command execution. This avoids changing a correct expression to solve a bundler problem.

11. Or skip the browser setup

If your goal is a clean image of a page rather than running a browser test, ScreenshotNeo provides a single screenshot request. Its consent step accepts cookie banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. It also includes an MCP server for AI agents through take_screenshot, get_page_info, and capture_pdf.

ScreenshotNeo removes common consent banners and overlays before returning the page image.
ScreenshotNeo removes common consent banners and overlays before returning the page image.

Read the complete option list in the ScreenshotNeo API documentation. cURL:

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://stripe.com \
  -o shot.webp

Python:

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({
  access_key: 'YOUR_API_KEY',
  url: 'https://stripe.com'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const body = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', body);

There are 1,000 free screenshots each month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account.

12. FAQ

Does changing Given to When fix an undefined step?

No. Matching uses the expression and the text after the keyword. Changing the keyword alone does not repair a mismatch.

Can one definition be shared by several features?

Yes. Put it in a shared directory and add an explicit glob, while keeping the pattern narrow enough to avoid duplicate matches.

Why did the error become ambiguous after I fixed the glob?

The file is now discovered, but more than one expression matches the same step. Remove the duplicate or narrow one expression.

What should I inspect first in CI?

Verify the installed package and lockfile, the configuration file used in CI, the feature and step paths, and the preprocessor debug output.

Is a bundler error the same as an undefined step?

No. Undefined is a matching or discovery result. A compiler error is a preprocessing problem and should be debugged in the bundler layer.