Cypress 03 ๐ฒ Writing Your First Test โ describe, it, and cy.visit
A Cypress test file is a Mocha-style suite: describe groups the tests, it declares a case, and cy commands drive the browser. The structure is familiar to anyone who has written Mocha or Jest, but the execution model is not: the cy commands do not return Promises that the test awaits. They are appended to a command queue, and the test function returns before the commands have run. The queue executes after the function returns, in order, with retry and auto-waiting applied to each command.
This chapter covers the test file structure, the cy.visit navigation, and the command queue model that makes Cypress’s assertions and actions behave differently from an async/await test runner. The sections that follow walk through the describe/it structure, the first commands, and the queue semantics that explain why cy commands are not awaited.
Key point: Cypress tests use describe and it, and the cy commands are enqueued, not awaitedโthe test function returns before the commands execute, and the queue runs them in order with automatic retry.
a. The test file structure
A Cypress E2E test lives in cypress/e2e/ and has a .cy.js or .cy.ts suffix. The file contains one or more describe blocks, each with one or more it blocks. The describe and it come from Mocha, which Cypress bundles; they are global, so no import is needed in a JavaScript test file .
// cypress/e2e/login.cy.js
describe("login", () => {
it("signs in and shows the dashboard", () => {
cy.visit("/login");
cy.get('[data-testid="email"]').type("user@example.com");
cy.get('[data-testid="password"]').type("password123");
cy.get('button[type="submit"]').click();
cy.url().should("include", "/dashboard");
});
});
The describe callback runs immediately during collection; the it callback runs when the test executes. The distinction matters because a cy command outside an it blockโin a before hook, for exampleโruns in the context of the first test that follows it, not at collection time . The hooks before, beforeEach, afterEach, and after are the Mocha hooks, and they follow the same outermost-first/inner-most-first order as Vitest.
The baseUrl in cypress.config.js makes cy.visit("/login") resolve to the configured origin. Without it, cy.visit needs an absolute URL, and the test is tied to a specific environment.
// cypress.config.js
const { defineConfig } = require("cypress");
module.exports = defineConfig({
e2e: {
baseUrl: "http://localhost:3000",
},
});
b. cy.visit and the first commands
cy.visit(url) navigates the browser to the URL and waits for the page’s load event. The second argument accepts options like timeout, onBeforeLoad, and failOnStatusCode .
cy.visit("/login"); // resolves against baseUrl
cy.visit("https://example.com");
cy.visit("/slow", { timeout: 60_000 });
After the visit, the commands chain: cy.get(selector) finds an element (and retries until it exists), .type(text) types into it, .click() clicks it, and .should(assertion) asserts on it with retry. Each command returns a cy chain object, not a Promise, which is why the calls are chained rather than awaited.
cy.get('[data-testid="email"]')
.type("user@example.com")
.should("have.value", "user@example.com");
The .should() assertion retries until it passes or the command timeout expires. cy.get() retries until the element exists. cy.contains(text) retries until an element containing the text exists. The retry is built into the command, not added by the test author .
c. The command queue and why cy is not awaited
The defining difference between Cypress and an async/await runner is the command queue. When the test function calls cy.visit() and cy.get(), those calls enqueue commands and return immediately. The test function returns, and then Cypress runs the queue: visit, get, type, click, assert. Each command waits for the previous one to finish, and each applies its own retry logic.
it("demonstrates the queue", () => {
cy.visit("/"); // enqueued
cy.get("h1").should("exist"); // enqueued
console.log("after"); // runs BEFORE the commands execute
});
The console.log runs before the visit, because the test function returned before the queue started. This is why cy commands cannot be used in a Promise.then or an async function that awaits them; the queue is the sequencing mechanism, not the Promise.
The consequence for variables is that a value extracted from a cy command is not available synchronously. const text = cy.get("h1").text() does not assign the text; it assigns the chain object. The correct pattern is .then() or an alias:
// WRONG: text is a chain object, not a string
const text = cy.get("h1").invoke("text");
// RIGHT: use .then()
cy.get("h1").invoke("text").then((text) => {
expect(text).to.equal("Welcome");
});
// RIGHT: use an alias
cy.get("h1").invoke("text").as("heading");
cy.get("@heading").then((text) => { ... });
The queue is the reason Cypress tests are written as chains rather than async/await sequences. The chain describes the order; the queue enforces it; the retry applies to each command independently.
Complete Example Session
// ============================================
// PART 1: THE CONFIG (BASE URL)
// ============================================
// cypress.config.js
const { defineConfig } = require("cypress");
module.exports = defineConfig({
e2e: {
baseUrl: "http://localhost:3000",
},
});
// ============================================
// PART 2: THE FIRST TEST
// ============================================
// cypress/e2e/home.cy.js
describe("home page", () => {
it("shows the welcome heading", () => {
cy.visit("/");
cy.get("h1").should("contain", "Welcome");
});
});
// ============================================
// PART 3: A TEST WITH ACTIONS
// ============================================
describe("search", () => {
it("returns results for a query", () => {
cy.visit("/");
cy.get('[data-testid="search"]').type("playwright");
cy.get('button[type="submit"]').click();
cy.get('[data-testid="result"]').should("have.length", 3);
});
});
// ============================================
// PART 4: THE QUEUE AND .THEN()
// ============================================
describe("queue", () => {
it("extracts text with .then()", () => {
cy.visit("/");
cy.get("h1")
.invoke("text")
.then((text) => {
expect(text).to.equal("Welcome");
});
});
});
The parts covered the base URL config, the first test with cy.visit and a retrying assertion, a test with actions and a length assertion, and the .then() pattern for extracting a value.
Quick Reference
Test Structure
| Element | Source |
|---|---|
describe(name, fn) | Mocha (global) |
it(name, fn) | Mocha (global) |
beforeEach(fn) | Mocha hook |
cy.* | Cypress global |
First Commands
| Command | Effect |
|---|---|
cy.visit(url) | Navigate, wait for load |
cy.get(selector) | Find element, retry until exists |
cy.contains(text) | Find element containing text |
.type(text) | Type into element |
.click() | Click element |
.should(assertion) | Retry assertion until pass |
The Queue
| Behavior | Detail |
|---|---|
cy returns | Chain object, not Promise |
| Test function | Returns before commands run |
| Sequencing | The queue, in order |
| Value extraction | .then() or alias |
Best Practices
โ Do This:
// Chain the commands
cy.get('[data-testid="email"]').type("a@b.com"); // โ
// Use .should for assertions
cy.get("h1").should("contain", "Welcome"); // โ
// Extract values with .then
cy.get("h1").invoke("text").then((t) => expect(t).to.equal("Welcome")); // โ
// Set baseUrl in the config
e2e: { baseUrl: "http://localhost:3000" } // โ
โ Don’t Do This:
// Assign the chain object
const text = cy.get("h1").text(); // not a string // โ
// Use async/await with cy
it("x", async () => { await cy.visit("/"); }); // โ
// Use hard-coded waits
cy.wait(2000); // โ
// Put cy commands outside it/hooks
cy.visit("/"); // at file scope // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Value is a chain object | Assigned cy result directly | Use .then() or alias |
await cy does nothing useful | Cypress does not return Promises | Chain the commands |
cy at file scope fails | Commands must run in a test or hook | Move inside it or beforeEach |
| Assertion runs too early | Read-then-assert instead of .should | Use .should() |
Real-World Examples
1. Visit and assert
cy.visit("/");
cy.title().should("include", "My App");
2. Type and click
cy.get('[data-testid="email"]').type("a@b.com");
cy.get("button").click();
3. Extract with .then
cy.get("h1").invoke("text").then((t) => expect(t).to.equal("Welcome"));
4. Use an alias
cy.get("h1").invoke("text").as("heading");
cy.get("@heading").then((t) => { ... });
5. Base URL config
e2e: { baseUrl: "http://localhost:3000" }
6. Contains
cy.contains("Welcome").should("be.visible");
7. Length assertion
cy.get("li").should("have.length", 3);
8. Hook
beforeEach(() => { cy.visit("/"); });
9. should with callback
cy.get(".msg").should(($el) => { expect($el).to.have.text("Saved"); });
10. cy.log
cy.log("starting search test");
Visual
The Command Queue
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ TEST FUNCTION โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ cy.visit("/") โ enqueue โ โ
โ โ cy.get("h1") โ enqueue โ โ
โ โ .should("exist") โ enqueue โ โ
โ โ return โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ โ
โ โผ โ
โ QUEUE RUNS โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ 1. visit / โ โ
โ โ 2. get h1 (retry until exists) โ โ
โ โ 3. assert exists (retry until pass) โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Why .then() Is Needed
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ const text = cy.get("h1").invoke("text"); โ
โ โ โ
โ โผ โ
โ text is a chain object, not the string โ
โ โ
โ cy.get("h1").invoke("text").then((text) => { โ
โ expect(text).to.equal("Welcome"); โ
โ }); โ
โ โ โ
โ โผ โ
โ The callback runs after the command completes. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
cy vs async/await
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CYPRESS ASYNC/AWAIT โ
โ โโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ cy.visit("/") โ โ await page.goto("/") โ โ
โ โ cy.get("h1") โ โ await locator.click()โ โ
โ โ .should("exist") โ โ expect(...).toBe... โ โ
โ โ โ โ โ โ
โ โ Queue, not Promise โ โ Promise, awaited โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Test structure | describe + it (Mocha) |
| Navigation | cy.visit(url) |
| First find | cy.get(selector) |
| Retry assertion | .should(assertion) |
| Command model | Queue, not Promise |
| Value extraction | .then() or alias |
| Base URL | cypress.config.js e2e.baseUrl |
Key takeaways:
- A Cypress test is a Mocha suite.
describegroups,itdeclares, and the hooks arebeforeEachand friends. The globals are available without import . - The
cycommands are enqueued, not awaited. The test function returns before the commands run, and the queue executes them in order with retry.await cy.visit()does nothing useful becausecydoes not return a Promise . .should()retries;cy.get()retries. The assertion and the element lookup both wait until the condition is met or the timeout expires, which is why the test does not need explicit waits .- Values are extracted with
.then()or aliases.const text = cy.get("h1").text()assigns the chain object, not the string. The callback in.then()receives the resolved value . - The
baseUrlmakescy.visitrelative. Without it, the test needs absolute URLs and is tied to one environment .
Remember: Cypress tests read as a chain of commands, and the chain is the sequencing. The test function builds the queue; the queue runs the commands; each command retries until it succeeds. Do not await a cy command, do not assign its result synchronously, and do not put commands outside an it or a hook. Use .should() for assertions and .then() for values. The queue is the model, and the chain is how the test describes what the user does.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!