Behavior Driven Development (abbr. BDD) encourages teams to use conversation and concrete examples to formalize a shared understanding of how the application should behave. BDD is largely facilitated through the use of a simple domain-specific language (DSL) using natural-language constructs (e.g., English-like sentences) that can express the behaviour and the expected outcomes.
Cucumber uses Gherkin to define test cases. Its syntax centers around a line-oriented design, similar to that of Python.
Scenario: Eric wants to withdraw money from his bank account at an ATM
Given Eric has a valid Credit or Debit card
And his account balance is $100
When he inserts his card
And withdraws $45
Then the ATM should return $45
And his account balance is $55
We define common steps in namespaced files of the common
folder i.e.
/cypress/integration/common/steps.js
. These files contain steps that we want to repeat in
various tests.
Example: /cypress/integration/common/steps.js
import { When } from "cypress-cucumber-preprocessor/steps";
When(/^the user is on the root page$/, function () {
cy.visit("/");
});
We write easy to understand, testable features.
- Define a
Background
if given - Define a
Scenario
as often as given - Describe the expected behavior
Example: /cypress/integration/Load.feature
Feature: Load
As a user,
I want to see the page,
so that I can use the app.
Scenario: The user wants to see the page
When the user is on the root page
Then the page is displayed
The keywords And
and But
are syntactic sugar for Given
, When
and Then
. They should not be
used in step definitions, use the corresponding keyword instead.
We separate steps and assertions:
Example: /cypress/integration/common/steps.js
import { When } from "cypress-cucumber-preprocessor/steps";
When(/^the user is on the root page$/, function () {
cy.visit("/");
});
Example: /cypress/integration/common/assertions.js
import { Then } from "cypress-cucumber-preprocessor/steps";
Then(/^the page is displayed$/, function () {
cy.get("#__next").should("exist");
});
To ensure that tested elements can be selected we add
data-attributes
to our target elements.
Usage | Pattern | example | description |
---|---|---|---|
ID | data-test-id |
data-test-id="my-element" |
Find element in the DOM |
- User stories and BDD: https://cucumber.io/blog/bdd/user-stories-are-not-the-same-as-features/
- Gherkin reference: https://cucumber.io/docs/gherkin/reference/