BDD helpers for Jest tests.
.feature ✨ <---> ✨ .test.ts
npm install specjest --save-devflowchart LR
F[.feature] -->|specjest test| T[.test.ts]
T2[.test.ts] -->|jest --json| J[JSON]
J -->|specjest feat| F2[.feature]
Convert a .feature file into a Jest test with test.todo() stubs.
npx specjest test path/to/file.featureInput (user.feature):
Feature: Create User
Scenario: Valid user
Given a new user
When data is submitted
Then user is savedOutput (user.test.ts):
describe(`Feature: Create User`, () => {
describe(`Scenario: Valid user`, () => {
describe(`Given a new user`, () => {
describe(`When data is submitted`, () => {
test.todo(`Then user is saved`);
});
});
});
});Generate .feature files from existing Jest tests.
npx jest --json | npx specjest featOr for specific tests:
npx jest user.test.ts --json | npx specjest featTests must use Gherkin prefixes: Feature:, Scenario:, Given, When, Then, And.
Add global BDD functions (feature, scenario, given, when, then) with colored output.
⚡ Quick setup - import the preset:
// jest.setup.ts
import "specjest/bdd";// jest.config.js
module.exports = {
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"]
};That's it! 🎉 All BDD globals are now available.
🔧 Custom setup - configure formatting manually
jest.setup.ts:
import { applyFormatting } from "specjest";
declare global {
function feature(name: string, fn: () => void): void;
function scenario(name: string, fn: () => void): void;
function given(name: string, fn: () => void): void;
function when(name: string, fn: () => void): void;
function then(name: string, fn?: jest.ProvidesCallback, timeout?: number): void;
}
globalThis.feature = applyFormatting(describe, ({ description, color, bold }) =>
color("magenta", `Feature: ${bold(description)}`)
);
globalThis.scenario = applyFormatting(describe, ({ description, color, bold }) =>
color("cyan", `Scenario: ${bold(description)}`)
);
globalThis.given = applyFormatting(describe, ({ description, color, bold }) =>
color("blue", `Given ${bold(description)}`)
);
globalThis.when = applyFormatting(describe, ({ description, color, bold }) =>
color("yellow", `When ${bold(description)}`)
);
globalThis.then = applyFormatting(it, ({ description, color, bold }) =>
color("green", `Then ${bold(description)}`)
);Usage:
feature("User Registration", () => {
scenario("Valid input", () => {
given("a new email", () => {
when("form is submitted", () => {
then("user is created", () => {
expect(true).toBe(true);
});
});
});
});
});| Command | Description |
|---|---|
specjest test <file.feature> |
📄 ➡️ 🧪 Convert feature to test |
jest --json | specjest feat |
🧪 ➡️ 📄 Convert tests to features |
specjest |
❓ Show help |
Recognized prefixes: Feature:, Scenario:, Given, When, Then, And
MIT
