Cucumber Test Data: Short Examples Tables, Seeded JSON Fixtures
Cucumber test data usually starts in the right place: a Scenario Outline with a short Examples table that product, QA and developers can all read. Then the edge cases arrive. Each new rule adds a column, each bug report adds a row, and a year later the table is 40 rows of names, emails and weights where nobody can tell which cell a row is actually testing. This post splits that table in two. The Gherkin keeps what a reader needs, a case name and the expected outcome. A generated, seeded JSON fixture holds the full input for every case, including planted invalid and boundary rows, and the step definitions look each row up by its key.
JsonFabrica generates the fixture, and it's only a JSON-over-HTTP API. There's no Cucumber plugin, Gherkin extension or SDK. The only npm package is the MCP server for AI coding agents, which has nothing to do with test runners. A short Node script calls the API and commits the result, and your step definitions read that file with plain JavaScript. Cucumber runs never touch the network.
The code below was run with cucumber-js 13.3.0 on Node 24, in an ES module project. The fixture was rendered with the JsonFabrica template engine, and the regen script was run against a local stand-in for the API that uses the same engine. Every passing and failing output shown is from a real run. The hand-written "before" table in the first section is the only example that wasn't executed.
Cucumber test data that outgrows the Examples table
The running example is parcel booking. A booking is accepted when the recipient has a name and a valid email address, lives in Germany, and the parcel weighs from 0.1 kg to 31.5 kg. Written the usual way, the outline puts every input in the Examples table:
Scenario Outline: Booking validation
Given a recipient "<name>" with email "<email>" in <country>
And a parcel weighing <kg> kg
When the customer books the parcel
Then the booking is <result>
Examples:
| name | email | country | kg | result |
| | [email protected] | DE | 2.5 | rejected |
| Hans Weber | hans.weber.example.com | DE | 4 | rejected |
| Anna Koch | [email protected] | CH | 1.2 | rejected |
| Peter Braun | [email protected] | DE | 0.1 | accepted |
| Eva Schulz | [email protected] | DE | 0.09 | rejected |
| Jan Roth | [email protected] | DE | 31.5 | accepted |
| Lena Vogt | [email protected] | DE | 31.51 | rejected |
| Jürgen Wolf | [email protected] | DE | 12 | accepted |
This table already has the street and city columns left out, and it has a few problems that grow with every row:
- The reason a row exists is invisible. Row two is there for the
missing
@, but you only find that out by checking each cell against the rules. Row one's defect is an empty cell, which is easy to miss in review and easy to "fix" by accident. - Most cells are filler. Each row needs a full, valid booking so it can fail for exactly one reason, so most of the table is names and addresses nobody cares about.
- The happy path is thin. Apart from the two boundary weights there's one valid row, and every new one is hand-typed.
Scenario Outline test data: a case key and an outcome
The split keeps the Examples table to two columns. Each case name says what the row is for, and the result says what should happen:
Feature: Parcel booking validation
We accept a booking when the recipient has a name and a valid
email address, lives in Germany, and the parcel weighs from
0.1 kg to 31.5 kg. Each case names a generated booking in
features/fixtures/bookings.json.
Scenario Outline: <case> is <result>
When the customer books the "<case>" parcel
Then the booking is <result>
Examples: Recipient details
| case | result |
| missing-name | rejected for name |
| bad-email | rejected for email |
| outside-service | rejected for country |
@weight
Examples: Weight limits
| case | result |
| min-weight | accepted |
| under-min-weight | rejected for weight |
| max-weight | accepted |
| over-max-weight | rejected for weight |
Scenario: Everyday bookings are accepted
When the customer books every "valid" parcel
Then every booking is accepted
A few Gherkin details are doing work here:
- One outline can have several Examples blocks. Each block gets its own name, so the table reads as grouped rules, not one long list.
- Tags work on an Examples block.
@weightapplies to the four scenarios generated from that block, so--tags @weightruns just the weight limits. - Placeholders work in the scenario name.
<case> is <result>becomes "max-weight is accepted", so each row reports under a readable name. - The limits stay in the feature description. The case names point at the rules ("max-weight") and the description states them (31.5 kg), so a reader doesn't need the fixture to know what's being tested.
- The bulk rows get their own scenario. The fixture holds a dozen ordinary valid bookings. Listing each in the table would bring the long table back, so one scenario books all of them and expects every one to be accepted.
The code under test is one function, standing in for whatever your When step really calls:
// src/booking.js
const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
export function bookParcel({ recipient, weightKg }) {
const errors = [];
if (recipient.name.trim() === "") errors.push("name");
if (!EMAIL.test(recipient.email)) errors.push("email");
if (recipient.country !== "DE") errors.push("country");
if (!(weightKg >= 0.1 && weightKg <= 31.5)) errors.push("weight");
return errors.length > 0
? { status: "rejected", errors }
: { status: "accepted" };
}
BDD test data from a seeded template
The fixture comes from one template. Rows 1 to 7 are planted cases, chosen by loop index. Every row after that is an ordinary valid booking:
{
"cases": [
<for(i, 1, getParam('cases', 20))><if(getVar('i') > 1)>,<endIf>
{
"key": <if(getVar('i') == 1)>"missing-name"
<elseIf(getVar('i') == 2)>"bad-email"
<elseIf(getVar('i') == 3)>"outside-service"
<elseIf(getVar('i') == 4)>"min-weight"
<elseIf(getVar('i') == 5)>"under-min-weight"
<elseIf(getVar('i') == 6)>"max-weight"
<elseIf(getVar('i') == 7)>"over-max-weight"
<else>"valid-<appendBefore('0', getVar('i'), 2)>"<endIf>,
"recipient": {
"name":
<if(getVar('i') == 1)>""<else>"<getRandomFullName('de')>"<endIf>,
"email":
<if(getVar('i') == 2)>"<toLowerCase(getRandomName())>.example.com"
<else>"<getRandomEmail('example.com')>"<endIf>,
"street": "<getRandomStreet('de')>",
"city": "<getRandomCity('de')>",
"country": <if(getVar('i') == 3)>"CH"<else>"DE"<endIf>
},
"weightKg": <if(getVar('i') == 4)>0.1
<elseIf(getVar('i') == 5)>0.09
<elseIf(getVar('i') == 6)>31.5
<elseIf(getVar('i') == 7)>31.51
<else><getRandomNumber(0.5, 30, 1)><endIf>
}<end_for>
]
}
What each part does:
- Each planted row breaks one rule. Row 1 has an empty name, row 2
an email with no
@, built fromtoLowerCaseand a random first name, and row 3 a Swiss address. All their other fields are ordinary valid values, so each one can only fail for its own reason. - The weight rows sit on and just past each limit. 0.1 and 31.5 must be accepted, 0.09 and 31.51 rejected. An off-by-one in either comparison fails one of the four. The post on composing edge cases goes further into choosing values like these.
- The keys are stable. The planted keys are fixed strings, and
appendBeforeturns the loop index intovalid-08,valid-09and so on. The same key names the same kind of row at every seed, which is what lets the Gherkin refer to it. - The valid rows look German. The
'de'locale givesgetRandomFullName,getRandomStreetandgetRandomCityGerman names, streets and cities, umlauts included. That matters later. - There are no variables. No value is used twice, so every field is written inline.
Template expressions support comparisons (==, !=, <, <=, >,
>=) and &&/||, but no arithmetic, which is why the boundary
weights are written out rather than computed from the limits. for
bounds are inclusive, the loop bound reads the cases param with
getParam, and the
<if(getVar('i') > 1)>,<endIf> guard puts a comma before every item
except the first. The control flow docs cover
for and if/elseIf/else. Keep cases at 8 or more, or some
planted rows, or all the valid ones, won't be generated.
What seed 1117 produces
Rendered with seed 1117 and the default 20 cases, the fixture starts
like this, trimmed here to the first case and valid-10:
{
"seed": 1117,
"cases": [
{
"key": "missing-name",
"recipient": {
"name": "",
"email": "[email protected]",
"street": "Dorfstraße 124",
"city": "Stuttgart",
"country": "DE"
},
"weightKg": 16.7
},
{
"key": "valid-10",
"recipient": {
"name": "Claudia Schröder",
"email": "[email protected]",
"street": "Dorfstraße 105",
"city": "Dortmund",
"country": "DE"
},
"weightKg": 6.8
}
]
}
The seed key isn't part of the template. The regen script adds it
from the API response, so the file records how to rebuild itself.
Regenerating the fixture with a Node script
The regen script is the only code that talks to JsonFabrica. It sends
the raw template to
POST /v1/templates/generate, which
renders a template without saving it, and writes the result next to
the feature files:
// Regenerates features/fixtures/bookings.json from scripts/bookings.tmpl.
// node scripts/regen-bookings.mjs # pinned seed, no diff
// node scripts/regen-bookings.mjs --seed 4711 # rebuild a logged seed
// node scripts/regen-bookings.mjs --random # API picks the seed
// Review the diff and commit. Cucumber runs never call the API.
import { readFile, writeFile } from "node:fs/promises";
import { parseArgs } from "node:util";
const API = "https://api.jsonfabrica.com/v1/templates/generate";
const { values } = parseArgs({
options: { seed: { type: "string" }, random: { type: "boolean" } },
});
// change the pinned seed only when you mean to replace the data
const seed = values.random ? undefined : Number(values.seed ?? 1117);
const res = await fetch(API, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.JSONFABRICA_API_KEY}`,
},
body: JSON.stringify({
body: await readFile(new URL("bookings.tmpl", import.meta.url), "utf8"),
params: { cases: 20 },
seed, // omitted from the JSON when undefined
}),
});
// errors arrive as {"error": {"code", "message", "details"}}
if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`);
const { data, meta } = await res.json();
const fixture = { seed: meta.seed, ...data };
const out = new URL("../features/fixtures/bookings.json", import.meta.url);
await writeFile(out, JSON.stringify(fixture, null, 2) + "\n");
console.log(`seed ${meta.seed}: ${data.cases.length} cases`);
It needs nothing beyond Node's built-in fetch and parseArgs, so it
adds no dependencies. Things worth knowing about the request and
response:
- The response is
{ data, meta }.datais the generated document.meta.seedis the seed that was used, either the one you sent or, with--random, the one the API picked.meta.generatedAtis left out of the file because it changes on every call. - Same template, seed and params give the same file. Running the
script with the pinned seed produces no diff. Editing the template or
changing
casesshifts the random draws, so commit the template and the fixture together. - The row count is a param, not a second template. A smoke job can
render the same template with
cases: 8, and a nightly job withcases: 200. The guide to reusable, parameterized templates covers driving one template with params like this. - The fixture lives under
features/, but cucumber-js by default only loads.js,.cjsand.mjsfiles from there as support code, so the JSON file is never mistaken for code.
JSONFABRICA_API_KEY=... node scripts/regen-bookings.mjs
npx cucumber-js
git add scripts/bookings.tmpl features/fixtures/bookings.json
cucumber-js step definitions that load rows by key
The step definitions read the fixture once, index it by key, and look up the row named in each step:
// features/step_definitions/booking.steps.js
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { When, Then } from "@cucumber/cucumber";
import { bookParcel } from "../../src/booking.js";
const file = new URL("../fixtures/bookings.json", import.meta.url);
const { seed, cases } = JSON.parse(readFileSync(file, "utf8"));
const byKey = new Map(cases.map((c) => [c.key, c]));
assert.equal(byKey.size, cases.length, "duplicate keys in bookings.json");
function bookingCase(key) {
const c = byKey.get(key);
if (!c) throw new Error(`no case "${key}" in bookings.json (seed ${seed})`);
return c;
}
When("the customer books the {string} parcel", function (key) {
this.result = bookParcel(bookingCase(key));
});
When("the customer books every {string} parcel", function (prefix) {
this.results = cases
.filter((c) => c.key.startsWith(`${prefix}-`))
.map((c) => ({ key: c.key, ...bookParcel(c) }));
assert.ok(this.results.length > 0, `no "${prefix}-" cases (seed ${seed})`);
});
Then("the booking is accepted", function () {
assert.deepEqual(this.result, { status: "accepted" }, `seed ${seed}`);
});
Then("the booking is rejected for {word}", function (field) {
const expected = { status: "rejected", errors: [field] };
assert.deepEqual(this.result, expected, `seed ${seed}`);
});
Then("every booking is accepted", function () {
const failed = this.results
.filter((r) => r.status !== "accepted")
.map((r) => `${r.key} rejected for ${r.errors.join(", ")}`);
assert.deepEqual(failed, [], `seed ${seed}`);
});
How the pieces fit:
- cucumber-js finds this file without configuration. By default it
runs
features/**/*.featureand loads support code from.js,.cjsand.mjsfiles underfeatures/. In a project with"type": "module"inpackage.json, these files are ES modules, soimport.meta.urlresolves the fixture relative to the step file. - The fixture is read once per process. It's read at module level,
when cucumber-js imports the file. With
--parallel, each worker imports it once. The file is read-only, so that's safe. - The outline steps match after substitution. Cucumber replaces
<result>before it matches steps, so the steps it sees are "the booking is accepted" and "the booking is rejected for weight". Two plain step definitions cover them.{string}and{word}are Cucumber Expression parameter types, and{string}strips the quotes. thisis the World. cucumber-js creates a new World object for every scenario and binds it asthisin each step. The When step storesthis.resultand the Then step reads it. Arrow functions would lose that binding, so the steps are regularfunctions.- Every assertion message names the seed. A failure in CI says which file produced it, even when the run used a random seed.
- The bookings and the Examples table can't silently drift apart.
An Examples row whose key isn't in the fixture fails with
no case "..." in bookings.json, and a template edit that duplicates a key fails on load.
If your When step drives a browser or calls an HTTP API rather than a function, the lookup stays the same and only the body of the step changes. The Playwright E2E post covers seeding the backend that such steps run against.
Running and debugging the Scenario Outline test data
With no arguments, cucumber-js runs everything, using its default progress formatter:
$ npx cucumber-js
................
8 scenarios (8 passed)
16 steps (16 passed)
0m 0.029s (0m 0.003s executing your code)
Each Examples row is its own scenario, with its own name. The
pretty formatter shows that, here for the weight rows only (location
comments removed to fit):
$ npx cucumber-js --tags @weight --format pretty
Feature: Parcel booking validation
@weight
Scenario Outline: min-weight is accepted
✔ When the customer books the "min-weight" parcel
✔ Then the booking is accepted
@weight
Scenario Outline: under-min-weight is rejected for weight
✔ When the customer books the "under-min-weight" parcel
✔ Then the booking is rejected for weight
@weight
Scenario Outline: max-weight is accepted
✔ When the customer books the "max-weight" parcel
✔ Then the booking is accepted
@weight
Scenario Outline: over-max-weight is rejected for weight
✔ When the customer books the "over-max-weight" parcel
✔ Then the booking is rejected for weight
4 scenarios (4 passed)
8 steps (8 passed)
0m 0.026s (0m 0.001s executing your code)
To show a failure, change the upper weight check in bookParcel from
<= to <. Only the row on the limit fails (the step-definition path
is shortened to fit; summary counts left out):
...........F....
Failed scenarios:
1) max-weight is accepted # features/booking.feature:22
Then the booking is accepted # .../booking.steps.js:29
AssertionError [ERR_ASSERTION]: seed 1117
+ actual - expected
{
+ errors: [
+ 'weight'
+ ],
+ status: 'rejected'
- status: 'accepted'
}
cucumber-js then prints the same difference a second time as a
JSON-style diff, left out here. The features/booking.feature:22 in
the first line is the Examples row, and passing it back reruns just
that row:
npx cucumber-js features/booking.feature:22
Pointing at line 7, the Scenario Outline: line, runs all seven rows
of the outline instead.
What the bulk rows catch
The planted rows test the rules someone wrote down. The bulk rows test what nobody thought to write down. Swap the empty-name check for a stricter one that only allows ASCII letters:
if (!/^[A-Za-z .'-]+$/.test(recipient.name)) errors.push("name");
Every planted row still passes: the empty name is still rejected, and at seed 1117 none of the other planted rows has an umlaut in its name. The everyday-bookings scenario fails, with one line per rejected row (diff repeat and summary counts left out):
...............F
Failed scenarios:
1) Everyday bookings are accepted # features/booking.feature:25
Then every booking is accepted # .../booking.steps.js:38
AssertionError [ERR_ASSERTION]: seed 1117
+ actual - expected
+ [
+ 'valid-10 rejected for name',
+ 'valid-12 rejected for name',
+ 'valid-13 rejected for name',
+ 'valid-18 rejected for name',
+ 'valid-19 rejected for name'
+ ]
- []
valid-10 is Claudia Schröder from the excerpt above. The other four
are two more Schröders, an Andrea Schäfer and a Jürgen Becker. The
hand-written table at the top happens to have one umlaut row, Jürgen
Wolf, but only because someone thought to type it. The generated rows
include names like these without anyone having to think of them.
Because the keys and their order don't depend on the seed, a scheduled
CI job can run node scripts/regen-bookings.mjs --random before
npx cucumber-js to vary the valid rows on every run. When it fails,
the seed is in the script's output and in every assertion message, and
node scripts/regen-bookings.mjs --seed <that seed> rebuilds the exact
file locally. That job shouldn't commit anything. The pinned seed stays
the one everyday runs use.
Gherkin Examples table vs data table
Gherkin has two kinds of table, and they do different jobs. Both appear in the same feature without conflict.
An Examples table belongs to a Scenario Outline. Cucumber runs the
outline once per row, substituting each <placeholder> in the steps,
and in the scenario name, with that row's values. Each row is a
separate scenario: it gets a fresh World, its own result and its own
line number to rerun.
A data table sits directly under a single step and is passed to that step's definition as its last argument:
Scenario: Supported destinations
Then bookings are accepted for these countries:
| country | name |
| DE | Germany |
Then("bookings are accepted for these countries:", function (table) {
// [{ country: "DE", name: "Germany" }]
const countries = table.hashes();
});
In cucumber-js the argument is a DataTable. hashes() uses the first
row as keys and returns one object per remaining row, rows() returns
the rows without the header, raw() returns everything, and
rowsHash() turns a two-column table into one object. The step runs
once, however many rows the table has.
So a data table hands one step a list or a record, and an Examples table repeats a whole scenario. The fixture approach in this post only changes how much an Examples row has to carry. It doesn't replace either kind of table. A data table is still the natural way to give one step a small, readable list like the one above.
The same pattern in Cucumber-JVM
Nothing here is specific to JavaScript. In Cucumber-JVM the feature
file is identical, since Gherkin and Cucumber Expressions are shared
across implementations. The Java step definitions use the same
expressions in annotations, such as
@When("the customer books the {string} parcel"). The fixture lives
under src/test/resources and is read with a JSON library such as
Jackson. Cucumber-JVM creates a new instance of each step-definition
class for every scenario, so instance fields play the role of the
World, and a dependency-injection module like PicoContainer shares
state between step classes. The regen script can stay in Node, or
become a curl call in the build. It only has to write the same file.
When an inline Examples table is still the right call
Don't move every Examples table into a fixture. Keep the data inline when both of these hold:
- The table is small. A handful of rows that fit on one screen don't need a fixture, a template and a regen script.
- The values are the requirement, and the people who own it edit it. A table of discount tiers, with "order total 49.99 gets 0%" and "50.00 gets 5%", is the spec itself. When product owners or QA review and change that table directly, as living documentation, hiding the numbers behind keys takes away the reason Gherkin is there.
The fixture earns its place under the opposite conditions: rows that are wide or numerous, cells that are mostly filler needed to make a valid request, and a happy path that should cover more than the few values someone typed. In this post's feature, the rules (31.5 kg, a valid email, Germany only) stay readable in Gherkin, and only the filler moved out. Many suites end up with both kinds of outline side by side.
FAQ
Can Cucumber load Examples from a JSON or CSV file?
Not natively. Gherkin has no syntax for importing Examples rows from
another file, so the table in the .feature file is the whole table.
The usual workaround is to keep a short key column in the Examples
table and have the step definition look up the full row in a JSON file
by that key. Community tools add it, either by generating the feature
file before Cucumber parses it (the gherking precompiler, for example)
or through a Cucumber-JVM plugin such as QAF's.
What is the difference between a data table and an Examples table in Cucumber?
An Examples table belongs to a Scenario Outline, and Cucumber runs the
outline once per row, replacing each <placeholder> in the steps with
that row's values. A data table sits directly under one step and is
passed to that step's definition as an extra, last argument. In
cucumber-js it arrives as a DataTable with methods such as
hashes(), rows() and rowsHash(). Use Examples to repeat a
scenario, and a data table to give one step a list or a record.
How do I share data between steps in cucumber-js?
Store values on this inside step functions. cucumber-js creates a
new World object for every scenario and binds it to this in each
step and hook, so a value set in a When step is visible in the
following Then step and gone by the next scenario. Step functions must
be regular functions, not arrow functions, or this will not be the
World. For more structure, register your own class with
setWorldConstructor.
How do I run a single Examples row in Cucumber?
Pass the feature file path with the line number of the row, for
example npx cucumber-js features/booking.feature:22 in cucumber-js.
Each Examples row runs as its own scenario, and pointing at the
Scenario Outline line instead runs all of its rows. You can also tag
an Examples block, such as @weight, and select it with
--tags @weight.
When should test data stay in the Gherkin Examples table?
Keep data inline when the table is short and the values themselves are the requirement, such as price tiers or a handful of thresholds, and especially when product owners or QA read and edit the table directly as living documentation. Move it into a fixture when rows are wide, numerous or mostly filler, and the reason each row exists gets lost among the columns.
Is there a JsonFabrica plugin for Cucumber or Gherkin?
No. JsonFabrica is a plain JSON-over-HTTP API, with no Cucumber or
Gherkin plugin, SDK or database connector. The only npm package is the
MCP server for AI coding agents, which has nothing to do with test
runners. You write a small regen script, in Node with fetch or with
curl, that sends a template and a seed to the API and writes the
generated JSON into your repository. Your step definitions read that
committed file, and Cucumber runs never call the API.
Generated Cucumber test data keeps your Examples tables short: a key
and an outcome in Gherkin, and the full rows, planted edge cases
included, in one committed file rebuilt from a seed. Rendering a raw
template with a seed and params is a single call to the JsonFabrica
API, documented with its { data, meta } response in the
templates API reference.
Generate realistic test data with JsonFabrica
Describe the shape of your data once, then generate as many fresh, realistic JSON documents as you need via a simple API call.