Principle:Nightwatchjs Nightwatch BDD Style Expect Assertions
| Knowledge Sources | |
|---|---|
| Domains | Testing, BDD, Assertions |
| Last Updated | 2026-02-12 00:00 GMT |
Overview
Behavioral-driven assertion pattern that provides human-readable, chainable test expectations using natural language chains.
Description
BDD-style expect assertions solve the readability problem in traditional assertion APIs by introducing natural language chains. Instead of `assert.equal(actual, expected)`, the BDD pattern uses `expect(actual).to.equal(expected)`. Language chain words like `to`, `be`, `been`, `is`, `that`, `which`, `and`, `has`, `have`, `with` serve purely as readability bridges and carry no assertion logic. The `.not` chain inverts the assertion. This pattern, popularized by Chai.js, enables assertions that read like English sentences while maintaining programmatic rigor.
In the context of Nightwatch, BDD assertions extend to DOM elements (`expect.element('#id').to.be.visible`), cookies (`expect.cookie('name').to.contain('value')`), page title, and URL. Assertions can include timeout behavior via `.before(ms)` and `.after(ms)`.
Usage
Use BDD-style expect assertions when writing tests that prioritize readability and when stakeholders (non-developers) may review test code. Prefer them over `assert.*` when testing element state, attribute values, text content, and visibility in an expressive chain.
Theoretical Basis
The core mechanism is chainable assertion composition:
- A subject is selected (element, cookie, title, URL).
- Language chains modify the internal assertion context (setting negation, deep equality flags).
- Terminal assertions (`equal`, `contain`, `match`, `startWith`, `endWith`) evaluate the condition.
- The assertion resolves as pass/fail with optional timeout retry.
Pseudo-code Logic:
# Abstract BDD assertion chain
chain = ExpectChain(subject)
chain.apply_modifiers(['to', 'be', 'not']) # 'not' sets negate flag
chain.evaluate('visible') # Terminal assertion
# If negate: assert NOT visible, else: assert visible
# Retry until timeout or assertion resolves