The tests you have written in the three previous lessons check Colmena's pieces separately: functions, components, views, stores, plugins and composables, each one mounted in jsdom with a test router and a made-to-measure mocked API. They are fast and precise, but none of them answers the question that really matters to the coworking space: can a member open the application in their browser, sign in, find a room, book it and cancel the booking? That is what end-to-end tests (E2E) are for: tests that start up the complete application, open a real browser and drive it as a person would, clicking buttons and typing into fields. In this lesson you will learn what they offer compared with unit tests and how much they cost, you will install and configure Cypress, you will start the application and the tests with a single command, you will write tests with robust selectors based on data-test attributes, you will control the initial state (storage, language and the simulated API's random failures), you will create a custom command for signing in and you will walk through the complete booking flow in Colmena.
Contents
- What an end-to-end test offers
- Installing and configuring Cypress
- Starting the application and the tests
- First test:
cy.visit,cy.get,cy.containsandshould - Robust selectors:
data-testattributes - Interactions: typing, clicking, choosing and ticking
- Assertions about the URL and navigation
- Automatic retries: why fixed waits are not needed
- Controlling the application's state
- Custom commands:
cy.signIn()withcy.session - Colmena's complete flow
- Language test
- Screenshots and videos
- Playwright, the alternative
- E2E tests in continuous integration
- Try it
- What an end-to-end test offers
1.1 What unit tests do not see
Go over what the tests in this module have never run: src/main.js and the order in which it installs the plugins; src/router/index.js with its guards, its createWebHistory and the lazy loading of the views; the download of the language before mounting; a real browser's localStorage and sessionStorage; the styles (a button covered by another element is invisible to jsdom); and the combination of all of this in a real sequence of screens. A bug in any of those places leaves Colmena unusable with every unit test green.
| Unit and integration (Vitest + VTU) | End-to-end (Cypress) | |
|---|---|---|
| What runs | One piece or a few, mounted by hand | The complete application, as it is published |
| Where | Node with jsdom | A real browser (Chrome, Firefox, Edge, Electron) |
| Dependencies | Mocked to measure (vi.mock, in-memory router) |
The real ones (in Colmena, the simulated API in src/api/, which is the application's "real" one) |
| How you interact | By calling functions and triggering events on a wrapper | As a user: the page, the mouse, the keyboard |
| Speed | Milliseconds per test | Seconds per test |
| When it fails | It points to the exact piece | It tells you which user step fails; you have to investigate why |
| Fragility | Low | Higher: more pieces, more timing, more state |
| Confidence it gives | That each piece fulfils its contract | That the user can do what they need to |
1.2 The cost
An E2E test is the most expensive in the pyramid from 08-01: it takes longer to run, needs the application up and running and a browser, and has more reasons to fail without the application being broken (a previous state that was not cleaned up, a response that takes longer than expected). That is why the strategy is to write few of them, focused on the user's critical journeys, and to leave the details and the edge cases to the unit tests. In Colmena, the critical journeys are few and clear:
- Signing in and returning to the screen that had been requested.
- Finding a room, booking it and seeing it in "My bookings".
- Cancelling a booking.
- Using the application in another language.
Whether the price is formatted correctly or whether the cancellation is rolled back if the API fails is already checked by the Vitest tests; repeating it in E2E would only add slowness.
- Installing and configuring Cypress
2.1 Installing
cypressinstalls the tool and, the first time, downloads its own binary (a few hundred megabytes, which are kept in a user cache and reused between projects).start-server-and-testis a small utility that starts a server, waits for it to respond and then runs the tests; we will use it in section 3.
2.2 cypress.config.js
At the root of the project, create cypress.config.js:
// cypress.config.js
import { defineConfig } from 'cypress'
export default defineConfig({
e2e: {
baseUrl: 'http://localhost:4173', // where Colmena will be while the tests run
specPattern: 'cypress/e2e/**/*.cy.js', // which files are tests
viewportWidth: 1280, // size of the browser window
viewportHeight: 800
}
})defineConfigonly serves to let the editor know the options. Aspackage.jsonhas declared"type": "module"since 01-03, the file usesimportandexport default.baseUrlis the application's address. With it, the tests write relative paths (cy.visit('/rooms')), and changing environment means changing one line. We use port 4173, the onevite previewuses, for the reasons we will see in section 3.specPattern: the Cypress tests will end in.cy.js, to tell them apart at a glance from the Vitest ones (.spec.js). Remember that in 08-01 we excluded thecypress/folder from Vitest: each tool runs only its own tests.- The window size sets the layout the test will see. If Colmena changed its menu on narrow screens, a test at an undefined size might or might not fail depending on the computer.
2.3 The folder structure
colmena-bookings/ ├── cypress/ │ ├── e2e/ ← the tests (*.cy.js) │ │ ├── catalog.cy.js │ │ ├── booking.cy.js │ │ └── language.cy.js │ ├── support/ │ │ ├── e2e.js ← loaded before each test file │ │ └── commands.js ← custom commands (section 10) │ ├── screenshots/ ← generated: screenshots (not committed to git) │ └── videos/ ← generated: videos (not committed to git) └── cypress.config.js
Create cypress/support/e2e.js with a single line for now (we will extend it in section 9):
And an empty cypress/support/commands.js, with a comment saying what it is for. Add to .gitignore:
If you run npx cypress open for the first time without these files, Cypress offers to create them for you, together with an example fixtures folder. Either route leads to the same place.
One last detail: ESLint does not know Cypress's global variables (cy, Cypress, describe, it, expect) and will flag them as undefined. The eslint-plugin-cypress package provides a recommended configuration that declares them; add it to eslint.config.js only for the files in cypress/, following the plugin's README for your version.
- Starting the application and the tests
3.1 Against which version of the application
An E2E test needs the application running at baseUrl. There are two options:
Development server (vite) |
Production build (vite build + vite preview) |
|
|---|---|---|
| What is tested | The code as it is written, with hot reloading | The code as it is published: bundled, minified, with the real lazy loading |
| Start-up | Immediate | It has to be built first (a few seconds) |
| Use | While you write tests (cypress open) |
Before publishing and in continuous integration (cypress run) |
We will use both: the development server for writing tests and the build for running them all.
3.2 cypress open and cypress run
| Command | What it does | When |
|---|---|---|
cypress open |
Opens the Cypress interface: you choose a browser and a file, you watch the application running, each command in a side list, and you can time travel by hovering over the steps | When writing and debugging tests |
cypress run |
Runs all the tests without an interface (headless), shows the result in the terminal and exits with an error code if any of them fails | Before publishing and in continuous integration |
3.3 The scripts
In package.json, add:
{
"scripts": {
"build:e2e": "vite build --mode e2e --outDir dist-e2e",
"preview:e2e": "vite preview --outDir dist-e2e --port 4173 --strictPort",
"dev:e2e": "vite --mode e2e --port 4173 --strictPort",
"test:e2e": "npm run build:e2e && start-server-and-test preview:e2e http://localhost:4173 \"cypress run --e2e\"",
"test:e2e:dev": "start-server-and-test dev:e2e http://localhost:4173 \"cypress open --e2e\""
}
}--mode e2emakes Vite load the variables in the.env.e2efile. We will use it in section 9 so that the simulated API does not fail at random during the tests. It is also the reason for building into a separate folder (--outDir dist-e2e): the test build must not replace the production build indist/.--port 4173 --strictPort: the same port asbaseUrlin both cases, and if it is taken, an error instead of silently choosing another one (the tests would point at a port where there is nothing).start-server-and-test <server> <url> <tests>runs thepreview:e2e(ordev:e2e) script, waits forhttp://localhost:4173to respond, runs Cypress and, when it finishes, stops the server. Without it you would have to start the server in one terminal and the tests in another.- The escaped double quotes (
\") groupcypress run --e2eas a single argument and work on Linux and macOS as well as in the Windows console, which does not understand single quotes.
From here on: npm run test:e2e:dev while you write tests and npm run test:e2e to run them all.
- First test:
cy.visit, cy.get, cy.contains and should
cy.visit, cy.get, cy.contains and shouldCreate cypress/e2e/catalog.cy.js:
// cypress/e2e/catalog.cy.js
describe('Room catalogue', () => {
it('is reached from the home page and shows the five rooms', () => {
cy.visit('/')
cy.contains('Colmena Bookings')
cy.contains('a', 'Rooms').click()
cy.location('pathname').should('eq', '/rooms')
cy.get('article').should('have.length', 5)
})
})Run npm run test:e2e:dev, choose E2E Testing, a browser and the catalog.cy.js file. You will see Colmena load in the right-hand panel and, on the left, the list of commands in green.
The pieces:
describeanditplay the same role as in Vitest (Cypress uses Mocha under the hood) andexpectis available with Chai's syntax (expect(x).to.eq(y)). They are not imported: they are globals in Cypress tests.cy.visit(path)loads a page, relative tobaseUrl, and waits for it to finish loading.cy.contains(text)looks for an element that contains that text;cy.contains(selector, text), one that also matches the selector. If it does not appear, the test fails. That is whycy.contains('Colmena Bookings')is already a check: "the header has been rendered".cy.get(selector)finds all the elements that match a CSS selector..click()clicks the element found..should(assertion, value)checks something about the result of the previous command:'eq'(equal),'have.length','contain'(contains a text),'have.text','have.attr','be.visible','be.disabled','exist'and their negations withnot.('not.exist').cy.location('pathname')gets the browser's current path.
Cypress commands do not return the elements; instead they are chained: each one receives the result (the "subject") of the previous one. And they do not run at the moment they are written: Cypress puts them in a queue and runs them in order, waiting for each one to finish. That is why there is no await or then in this test, even though loading the page, downloading the lazy views and requesting the catalogue from the API are asynchronous operations.
- Robust selectors:
data-test attributes
data-test attributes5.1 The problem with the first test
The test works, but it is fragile. cy.get('article') depends on each room being rendered with an <article>: if one day RoomCard switches to an <li>, or another <article> is added to the page (a notice, a piece of coworking news), the test fails or, worse, passes while counting the wrong things. cy.contains('a', 'Rooms') depends on the menu text: in Catalan it would be "Sales". And the temptation to use CSS classes (cy.get('.card')) is just as dangerous: classes exist for styling, and whoever changes them is thinking about the design, not about the tests.
| Selector | Example | Problem |
|---|---|---|
| Tag | cy.get('article') |
Changes with any tweak to the markup; not very specific |
| CSS class | cy.get('.card__actions button') |
Changes with any tweak to the styles; couples the test to the design |
| Identifier | cy.get('#room-polen') |
Better, but ids have other uses (anchors, label for) and not every element has one |
| Visible text | cy.contains('Book') |
Very good for what the user reads, but it changes with the language and the wording |
| Test attribute | cy.get('[data-test="room-card"]') |
None: it exists only for the tests, and anyone who sees it knows they must not change it |
Cypress's recommendation, and the one we will follow, is to add data-test attributes to the elements the tests interact with. data-* attributes are valid HTML, the browser ignores them and their name makes it clear what they are for. The visible text is still useful for checking what the user reads (should('contain', 'Néctar Room')); the attribute, for finding the element.
5.2 Adding them to Colmena
These are the attributes the tests in this lesson will use. Add them in each file:
<!-- src/components/AppHeader.vue: the main menu and the language selector -->
<nav class="header__menu" :aria-label="$t('menu.main')" data-test="main-menu">
<!-- ... -->
<select class="header__language" :value="locale" :aria-label="$t('menu.language')" data-test="language-select" @change="onLanguageChange"><!-- src/views/LoginView.vue: the two fields, the error and the button -->
<TextField v-model.trim="email" v-focus type="email" label="Email address"
autocomplete="username" data-test="login-email" />
<TextField v-model="password" type="password" label="Password"
autocomplete="current-password" data-test="login-password" />
<p v-if="error" class="error" role="alert" data-test="login-error">{{ translateError(error) }}</p>
<BaseButton type="submit" :disabled="submitting" data-test="login-submit"><!-- src/components/RoomCard.vue: the card and the link to the spec sheet -->
<article
class="card"
:class="[`card--${status}`, { 'card--selected': selected }]"
data-test="room-card"
...
>
<!-- ... -->
<RouterLink :to="{ name: 'room-detail', params: { id: room.id } }" class="card__link" data-test="spec-sheet-link"><!-- src/views/RoomDetailView.vue: the link to the form -->
<RouterLink v-if="room.available" :to="{ name: 'book', params: { roomId: room.id } }"
class="detail__book" data-test="book-room"><!-- src/components/BookingForm.vue: the fields the test will fill in -->
<TextField ref="date-field" v-model="form.date" type="date" ... data-test="booking-date" />
<select id="booking-start" v-model="form.startTime" ... data-test="booking-start-time">
<select id="booking-end" v-model="form.endTime" ... data-test="booking-end-time">
<TextField ref="attendees-field" v-model.number="form.attendees" type="number" ... data-test="booking-attendees" />
<input id="booking-rules" v-model="form.acceptsRules" type="checkbox" ... data-test="booking-rules" />
<BaseButton type="submit" data-test="booking-submit"><!-- src/views/dashboard/DashboardBookingsView.vue: the notice, each row (with its id) and the cancel button -->
<div v-if="newBooking" class="note new-booking-notice" role="status" data-test="new-booking-notice">
<!-- ... -->
<li
v-for="booking in visibleBookings"
:key="booking.id"
v-memo="[...]"
:class="{ 'booking-list__new': booking.id === newBookingId }"
data-test="booking"
:data-id="booking.id"
>
<!-- ... -->
<BaseButton v-if="booking.status !== 'cancelled'" variant="danger" ... data-test="cancel-booking">Three observations:
- On the
TextFields, the attribute reaches the<input>, not the root<div>, thanks to theinheritAttrs: falseandv-bind="$attrs"from 03-05. It is exactly what we want: the test types into the field. OnBaseButton, which has a single root element, it reaches the<button>. :data-id="booking.id"is dynamic: it identifies which booking each row is. We will use it to find the newly created booking among others.v-memodoes not affect it, because a row's id never changes.- The names follow a pattern (
area-element:login-email,booking-date) so that they are self-explanatory and do not clash. These attributes are also useful in Vue Test Utils tests:wrapper.get('[data-test="login-email"]').
Now rewrite the first test with them:
// cypress/e2e/catalog.cy.js
describe('Room catalogue', () => {
it('is reached from the home page and shows the five rooms', () => {
cy.visit('/')
cy.get('[data-test="main-menu"]').contains('a', 'Rooms').click()
cy.location('pathname').should('eq', '/rooms')
cy.get('[data-test="room-card"]').should('have.length', 5)
cy.contains('[data-test="room-card"]', 'Enjambre Auditorium').should('contain', 'Unavailable')
})
})cy.get(...).contains(...) searches inside the previous element: the "Rooms" link in the main menu, not any other. And cy.contains('[data-test="room-card"]', 'Enjambre Auditorium') finds the card that contains that name, in order to check something about it.
- Interactions: typing, clicking, choosing and ticking
Action commands simulate what the user does, with the same events the browser would generate:
| Command | What it does | Example in Colmena |
|---|---|---|
.type(text) |
Types key by key (triggers keydown, input, keyup...) |
cy.get('[data-test="login-email"]').type('[email protected]') |
.type('{enter}') |
Special keys between braces: {enter}, {esc}, {backspace}, {selectall} |
Submitting a form with Enter, closing the user menu with Escape |
.clear() |
Empties a field | cy.get('[data-test="booking-attendees"]').clear().type('6') |
.click() |
Clicks | cy.get('[data-test="login-submit"]').click() |
.select(value or text) |
Chooses an option in a <select> |
cy.get('[data-test="booking-start-time"]').select('10:00') |
.check() / .uncheck() |
Ticks or unticks a checkbox or a radio button | cy.get('[data-test="booking-rules"]').check() |
.focus(), .blur(), .trigger(event) |
Other events | cy.get('[data-test="booking-date"]').blur() |
Before each action, Cypress checks that the element is actionable: that it exists, is visible, is not disabled, is not covered by another element and is not being animated. If it is not, it waits (up to the maximum time) for it to become so. This catches real bugs that jsdom does not see, such as a button hidden behind a notice. If you ever need to skip the check, there is { force: true }, but use it as a last resort: the user cannot force anything.
For the date field, .type() needs the YYYY-MM-DD format, the same one <input type="date"> uses internally regardless of how the browser displays it.
- Assertions about the URL and navigation
In a SPA, the URL is part of the state (as you learnt in module 4), so checking it is as important as checking what is displayed:
cy.location('pathname').should('eq', '/dashboard/bookings') // the path
cy.location('search').should('contain', 'new=') // the query (?new=...)
cy.url().should('include', '/rooms/nectar') // the full URL
cy.location().should((location) => { // several things at once
expect(location.pathname).to.eq('/book/polen')
expect(location.search).to.eq('?attendees=3')
})
cy.go('back') // the browser's Back button
cy.reload() // reload the pagecy.location(part)returns a part ofwindow.location:pathname,search,hash... It is more precise thancy.url(), which returns the full URL with the domain.shouldwith a function lets you write several assertions withexpect. Cypress retries the whole function until they are all met, as we will see in the next section.cy.go('back')andcy.reload()test what unit tests could not: the browser's real history and reloading, with the session insessionStorageand the preferences inlocalStorage.
- Automatic retries: why fixed waits are not needed
Colmena does not respond instantly: the simulated API takes its time, the views are downloaded on demand and authentication waits 600 ms. The instinctive reaction is to wait:
// BAD: a fixed wait
cy.get('[data-test="login-submit"]').click()
cy.wait(2000) // "just in case"
cy.location('pathname').should('eq', '/dashboard/profile')It is an anti-pattern with two defects: if the server takes 2.1 seconds, the test fails; if it takes 0.1, you have wasted 1.9 seconds on every run, multiplied by every wait in every test.
Cypress solves the problem with automatic retries. Query commands (get, contains, find, location, url...) and the assertions chained to them are repeated over and over until the assertion is met or the maximum time runs out (4 seconds by default):
// GOOD: the assertion waits exactly as long as needed
cy.get('[data-test="login-submit"]').click()
cy.location('pathname').should('eq', '/dashboard/profile') // retries until the path changes| Type of command | Examples | Behaviour |
|---|---|---|
| Queries | get, contains, find, location, url |
Retried together with their assertions until they are met |
| Assertions | should, and |
Retried with the previous query |
| Actions | click, type, select, check |
Not retried, but they wait for the element to be actionable |
| Others | visit, reload, wait |
They wait for their own condition (the page loading...) |
Two practical consequences:
- End every action with an assertion about its effect (the URL changes, a text appears, a button disappears). That assertion is what waits, and it also documents what was supposed to happen.
- If something legitimately takes more than 4 seconds, increase the timeout for that query:
cy.get('[data-test="room-card"]', { timeout: 10000 }). Do not raise the global timeout for all of them.
cy.wait only makes sense for waiting for network requests intercepted with cy.intercept (cy.wait('@request')), which Colmena does not need because it does not make HTTP requests; when it does, they will be the tool for waiting for and simulating server responses, just like MSW in the unit tests (08-02).
- Controlling the application's state
9.1 Each test starts clean
An E2E test is only reliable if it knows where it is starting from. Cypress helps with test isolation, enabled by default: before each test it blanks the page and clears the cookies, localStorage and sessionStorage. No test inherits the session or the bookings from the previous one.
But Colmena keeps state in more places than it seems, and some of them depend on the environment:
| State | Where it lives | Risk in the tests |
|---|---|---|
| Bookings in the "database" | localStorage, colmena-api-bookings |
When it is empty, the API generates demo bookings with dates relative to today, which may overlap with the test's |
| Bookings cache | localStorage, colmena-cache-bookings |
The list appears before the API responds |
| Session | sessionStorage, colmena-session |
Without it, the protected routes lead to the login page |
| Language | localStorage, colmena-language; if it does not exist, navigator.languages |
The test browser may be set to another language (Spanish or Catalan, for example), and the whole interface would change |
| API failures | Math.random in failSometimes |
One in ten requests fails at random: the test would fail every now and then for no reason |
| API delay | randomDelay |
Up to 1.5 s per request: slow, erratic tests |
9.2 Seeding the storage before loading
cy.visit accepts the onBeforeLoad option, a function that receives the page's window before the application's code runs. It is the moment to prepare the storage, because Colmena reads it on start-up (initialLanguage(), the persistence plugin when it creates the stores):
cy.visit('/dashboard/bookings', {
onBeforeLoad(win) {
// The simulated API's "database", with a known booking
win.localStorage.setItem('colmena-api-bookings', JSON.stringify([
{ id: 'r-e2e-1', roomId: 'polen', date: '2026-12-01', startTime: '10:00', endTime: '12:00',
member: 'Laura Gómez', attendees: 3, status: 'confirmed', extraEquipment: [], notes: '' }
]))
// Laura is already signed in (what useSessionStore's persistence plugin will read)
win.sessionStorage.setItem('colmena-session', JSON.stringify({
name: 'Laura Gómez', email: '[email protected]', plan: 'flexible', role: 'member'
}))
// The interface, in Catalan
win.localStorage.setItem('colmena-language', 'ca')
}
})Notice that the test writes exactly the persisted formats we protected with tests in 08-03: the same keys and the same fields. Seeding the state like this is much faster than reaching it through the interface, and it is worth using in every test whose goal is not that journey. Signing in through the interface is tested once, in its own test; the others can start with the session already open.
9.3 A deterministic language for all the tests
initialLanguage() checks navigator.languages if there is no saved language, and the language of the browser Cypress uses depends on the machine running the tests: on a computer configured in Spanish or Catalan, Colmena would start in that language. So as not to have to seed the language in every cy.visit, set a default value for all the tests in cypress/support/e2e.js:
// cypress/support/e2e.js
// Runs before each test file
import './commands.js'
// Deterministic language: unless a test saves another one, Colmena starts in English,
// whatever the language of the browser running the tests
Cypress.on('window:before:load', (win) => {
if (!win.localStorage.getItem('colmena-language')) {
win.localStorage.setItem('colmena-language', 'en')
}
})Cypress.on('window:before:load', ...)runs on every page load, like a globalonBeforeLoad.- Only if there is no saved language: that way a test can ask for another one (as in the previous example or in the language test in section 12), and a reload keeps the language the application itself saved.
9.4 A stable simulated API for the tests
The most serious problem remains: the random failures and the delay in src/api/simulation.js. For the unit tests we solved them with vi.spyOn(Math, 'random'); in a real browser we do not have vi. The solution is for the simulation itself to offer a stable mode, activated in a controlled way only when building for the E2E tests.
At the root of the project, create the .env.e2e file:
Vite loads .env.[mode] when it runs with --mode [mode], and exposes the variables that start with VITE_ to the application as import.meta.env.VITE_.... The value is replaced at build time: in a normal build (npm run build), the variable does not exist and the stable mode cannot be activated in any way. That is why "a flag on window" is not enough on its own: anyone could type it into the console of the published application. Here the window flag is only taken into account if the build is already the test build.
Modify the beginning of src/api/simulation.js (the wait and errorWithStatus functions do not change):
// src/api/simulation.js
// Utilities for simulating a server: variable delay and occasional failures
const MIN_DELAY_MS = 300
const MAX_DELAY_MS = 1500
const ERROR_PROBABILITY = 0.1 // 10% of requests fail
// Stable mode for the E2E tests: no delay and no random failures.
// It only exists in builds made with --mode e2e (the .env.e2e file); in all others it is false.
const STABLE_SIMULATION = import.meta.env.VITE_STABLE_SIMULATION === 'true'
// Current settings of the simulation. In stable mode, a test can force failures
// by defining window.__colmenaSimulation = { errorProbability: 1 } before loading the page.
function settings() {
if (!STABLE_SIMULATION) {
return { withDelay: true, errorProbability: ERROR_PROBABILITY }
}
return { withDelay: false, errorProbability: 0, ...globalThis.__colmenaSimulation }
}
export function randomDelay() {
if (!settings().withDelay) return 0
return MIN_DELAY_MS + Math.random() * (MAX_DELAY_MS - MIN_DELAY_MS)
}
export function failSometimes() {
if (Math.random() < settings().errorProbability) {
throw errorWithStatus('Could not connect to the Colmena server', 503, 'connection')
}
}
// wait(ms, signal) and errorWithStatus(...), unchangedLet's analyse the design:
import.meta.env.VITE_STABLE_SIMULATION === 'true': environment variables are always strings, so it is compared with the string'true'.settings()is consulted on every request, not once when the module loads: that way a test can changewindow.__colmenaSimulationin the middle of the run (for example, so that a "Retry" works after a forced failure).globalThisis the global object in any environment (in the browser,window). The__prefix and the specific name make it clear that it is a test hook, not an API of the application.- With probability 0,
Math.random() < 0is never true: it never fails. With 1, it always fails. - A delay of 0 does not remove the asynchrony (
wait(0)is still asetTimeout): the application still shows its loading states for an instant, as with a fast network. - The Vitest tests do not change: they run in
testmode, without.env.e2e, and they still control chance withvi.spyOn(Math, 'random')as in 08-02. authenticatedoes not userandomDelay(it always waits 600 ms, since 05-03). There is no need to touch it: it is a fixed delay, and Cypress's retries absorb it.
Check the mode with npm run dev:e2e: as you navigate through Colmena, the catalogue and the bookings appear instantly and never fail. With npm run dev, everything stays as it always was.
- Custom commands:
cy.signIn() with cy.session
cy.signIn() with cy.sessionMany tests start with the session already open. Repeating the form's steps in each of them would be slow and verbose. Cypress lets you create your own commands with Cypress.Commands.add, and offers cy.session so as not to repeat the sign-in: the first time, it runs the steps and saves the resulting cookies, localStorage and sessionStorage; on subsequent occasions, it restores them directly.
Write in cypress/support/commands.js:
// cypress/support/commands.js
// Colmena's custom commands for the E2E tests
// cy.signIn(email?, password?): signs in through the interface only once per account
// and test file; in subsequent tests, it restores the saved session.
Cypress.Commands.add('signIn', (email = '[email protected]', password = 'colmena') => {
cy.session(['signIn', email], () => {
cy.visit('/login')
cy.get('[data-test="login-email"]').type(email)
cy.get('[data-test="login-password"]').type(password, { log: false })
cy.get('[data-test="login-submit"]').click()
cy.location('pathname').should('eq', '/dashboard/profile') // the session has started
})
})Cypress.Commands.add(name, function)registerscy.signIn(). Ascommands.jsis imported insupport/e2e.js, it is available in every test.- The default parameters sign in as Laura Gómez (member). For Marta Vidal (manager):
cy.signIn('[email protected]'). cy.session(id, setup): theididentifies the saved session (here, one per account). If it already exists, Cypress restores the storage and does not run the setup.- The setup ends with an assertion: if
cy.sessionsaved the storage before the sign-in had finished, it would save an empty session. Waiting for the path to be/dashboard/profileguarantees thatcolmena-sessionhas already been written. { log: false }prevents the password from appearing in the command list and in the videos. They are fictitious credentials, but it is a good habit.- After
cy.session, the page is left blank: each test must do its owncy.visit. On loading, the persistence plugin will readcolmena-sessionfromsessionStorageand the session will be active. cy.sessionaccepts a third option,validate, for checking that a restored session is still valid (for example, that a real server has not expired it). With Colmena's simulated session we do not need it.
- Colmena's complete flow
11.1 The journey
This is the test that justifies everything that came before: Colmena's most valuable journey, from start to finish.
flowchart LR
A["Sign in<br/>(cy.signIn)"] --> B["Filtered catalogue<br/>/rooms?floor=2&capacity=12"]
B --> C["Spec sheet<br/>/rooms/nectar"]
C --> D["Form<br/>/book/nectar"]
D --> E["My bookings<br/>/dashboard/bookings?new=..."]
E --> F["Cancel<br/>the booking"]
11.2 The test
Create cypress/e2e/booking.cy.js:
// cypress/e2e/booking.cy.js
import { dateInDays } from '../../src/utils/dates.js'
describe('Booking a room from start to finish', () => {
beforeEach(() => {
cy.signIn() // Laura Gómez, member
})
it('finds a room, books it and cancels the booking', () => {
const date = dateInDays(30) // always in the future, whatever day it runs
// 1. The catalogue, filtered from the URL: floor 2 and at least 12 people
cy.visit('/rooms?floor=2&capacity=12', {
onBeforeLoad(win) {
win.localStorage.setItem('colmena-api-bookings', '[]') // a "database" with no bookings
}
})
cy.get('[data-test="room-card"]').should('have.length', 1).and('contain', 'Néctar Room')
// 2. The room's spec sheet
cy.get('[data-test="spec-sheet-link"]').click()
cy.location('pathname').should('eq', '/rooms/nectar')
cy.contains('h2', 'Néctar Room')
// 3. The booking form
cy.get('[data-test="book-room"]').click()
cy.location('pathname').should('eq', '/book/nectar')
cy.get('[data-test="booking-date"]').type(date)
cy.get('[data-test="booking-start-time"]').select('10:00')
cy.get('[data-test="booking-end-time"]').select('12:00')
cy.get('[data-test="booking-attendees"]').clear().type('6')
cy.get('[data-test="booking-rules"]').check()
cy.get('[data-test="booking-submit"]').click()
// 4. The new booking, highlighted in "My bookings"
cy.location('pathname').should('eq', '/dashboard/bookings')
cy.get('[data-test="new-booking-notice"]').should('contain', 'Néctar Room')
cy.location('search')
.should('contain', 'new=')
.then((search) => {
const id = new URLSearchParams(search).get('new')
cy.get(`[data-test="booking"][data-id="${id}"]`).as('newBooking')
})
cy.get('@newBooking').should('contain', 'Néctar Room').and('contain', 'Confirmed')
// 5. Cancel it (Cypress automatically accepts the window.confirm)
cy.get('@newBooking').find('[data-test="cancel-booking"]').click()
cy.get('@newBooking').should('contain', 'Cancelled')
cy.get('@newBooking').find('[data-test="cancel-booking"]').should('not.exist')
})
})Let's go through the decisions:
import { dateInDays }reuses the application's utility from 05-02. Cypress bundles each test file, so it can import ordinary JavaScript modules with relative paths (the@alias belongs to Vite and does not exist here). A fixed date such as'2026-11-03'would make the test fail on the day it ended up in the past, because the form rejects dates earlier than today.- The catalogue is filtered from the URL: the filters have lived in the query since 04-05, so the test goes straight to the state it wants, without clicking any filters. Of the rooms on floor 2 (Néctar, 12 people, and Celda, 1), only Néctar holds 12 or more; and 12 is one of the minimums offered by the buttons in
RoomFilters, so it is a URL the user could have generated themselves. '[]'incolmena-api-bookings: the "database" starts empty, without the demo bookings that could overlap with the new one.cy.signIn()has already restored the session before thiscy.visit, so thisonBeforeLoadonly adds (or replaces) the bookings table.- An assertion after every action (the URL of each screen, the spec sheet's title): they mark the steps of the journey, wait for each screen to be ready and, if something fails, the report says at which step.
- The member is not typed in: the form fills it in from the session and makes it read-only for a member (04-06). If that rule broke, the submission would fail with a validation error and the test would stop at step 4.
.then(...)and.as(...): the booking's id is assigned by the API, so the test does not know it in advance. We read it from the?new=query withURLSearchParamsand create an alias for the row with thatdata-id.cy.get('@newBooking')looks the row up again each time, so it keeps working even if Vue re-renders it when cancelling..thenis not retried, which is why it comes after ashouldthat waits for the query to containnew=. It is the pattern for using a value from the page in the test's code.window.confirmis accepted automatically: Cypress answerstrueto all confirmation dialogs unless the test says otherwise withcy.on('window:confirm', () => false).- The optimistic cancellation is visible instantly ("Cancelled"), and the disappearance of the button checks the view's rule: cancelled bookings cannot be cancelled again.
Run it with npm run test:e2e:dev and watch the journey in the browser. Then hover over the command list: Cypress keeps a snapshot of the DOM at each step and shows you what the page looked like at that moment.
- Language test
Language is a good example of what only an E2E test really checks: the lazy download of the messages, the <html lang> attribute, the format of prices in the active language and the saved preference when reloading. Create cypress/e2e/language.cy.js:
// cypress/e2e/language.cy.js
describe('Interface language', () => {
it('starts in the saved language', () => {
cy.visit('/rooms', {
onBeforeLoad(win) {
win.localStorage.setItem('colmena-language', 'ca')
}
})
cy.get('html').should('have.attr', 'lang', 'ca')
cy.get('[data-test="main-menu"]').should('contain', 'Sales')
})
it('changes with the selector, adapts the formats and remembers it after reloading', () => {
cy.visit('/rooms')
cy.get('[data-test="main-menu"]').should('contain', 'Rooms')
cy.contains('[data-test="room-card"]', 'Panal Room').should('contain', '€25.00')
cy.get('[data-test="language-select"]').select('es')
cy.get('html').should('have.attr', 'lang', 'es')
cy.get('[data-test="main-menu"]').should('contain', 'Salas')
cy.contains('[data-test="room-card"]', 'Panal Room').should('contain', '25,00')
cy.reload()
cy.get('html').should('have.attr', 'lang', 'es')
cy.get('[data-test="main-menu"]').should('contain', 'Salas')
})
})- The first test seeds Catalan before loading: it checks that
initialLanguage()reads the saved preference, thatchangeLanguageactivates the language before mounting (thelang="ca"attribute on<html>) and that the downloaded messages are used in the interface ("Sales"). - The second seeds nothing: the
support/e2e.jsfrom section 9.3 guarantees that it starts in English. The change with.select('es')goes through the whole ofchangeLanguage: the download ofes.json(lazy, in the real build), thelangattribute, the texts and the format fromformatPluginconnected withlocaleIntl, which changes from "€25.00" to "25,00 €". cy.reload()checks that the preference was saved inlocalStorage: after reloading, the application starts directly in Spanish.
Compare this with the tests in 08-03: there we checked that formatPlugin follows the language with the localeIntl function; here, that the whole system does so in the browser. The unit test says which piece fails; the E2E test, that the user would notice.
- Screenshots and videos
When a test fails in cypress run, there is no interface to look at. Cypress helps with:
| Resource | How it is enabled | Where it is saved |
|---|---|---|
| Automatic screenshot on failure | By default (screenshotOnRunFailure: true) |
cypress/screenshots/ |
| Manual screenshot | cy.screenshot('name') at any point in the test |
cypress/screenshots/ |
| Video of each test file | The video: true option in cypress.config.js (disabled by default) |
cypress/videos/ |
// In booking.cy.js, after cancelling: a screenshot for documentation or visual review
cy.screenshot('my-bookings-after-cancelling')Screenshots on failure show the page at the exact moment of the error, with the command list next to it: they are almost always enough to understand what happened. Videos are useful in continuous integration, where you cannot watch the run, but they take up space and slow the tests down; enable them when you need them. Cypress empties both folders at the start of each cypress run, which is why we excluded them from git in section 2.
- Playwright, the alternative
Cypress is not the only E2E testing tool. Playwright, created by Microsoft, is today its main alternative, and npm create vue@latest offers it too:
| Cypress | Playwright | |
|---|---|---|
| Where the test runs | Inside the browser, alongside the application | Outside, controlling the browser through a protocol |
| Style | A chain of commands with a queue and implicit retries | Explicit async/await, with automatic waiting in its locators |
| Browsers | Chrome, Edge, Firefox, Electron (WebKit, experimental) | Chromium, Firefox and WebKit (Safari's engine) |
| Several tabs, windows or origins in one test | Limited | Supported |
| Parallel execution | With Cypress's cloud service or your own configuration | Included, free |
| Debugging | Interactive interface with time travel, very instructive | Very complete inspector and trace viewer |
| Component testing | Yes (Cypress Component Testing) | Experimental |
Both are good options. Cypress stands out for its interface and its learning curve; Playwright, for its browser coverage (Safari included) and parallelism. The principles of this lesson (few tests on critical journeys, data-test selectors, controlled state, no fixed waits) apply in exactly the same way to both.
- E2E tests in continuous integration
npm run test:e2e builds, starts the server, runs all the tests without an interface and exits with an error code if any of them fails: it is exactly what a continuous integration system needs, running the tests automatically on every change pushed to the repository and keeping the screenshots and videos of the failures. Setting it up, together with the Vitest tests, the build and the deployment, is the subject of Continuous Integration and Deployment (CI/CD).
- Try it
- Interactive mode. Run
npm run test:e2e:dev, choosebooking.cy.jsand watch the journey. Hover over the commands in the list: the page goes back to each step. Click onselect 10:00: the browser console shows the element and the command's subject. - Everything at once. Run
npm run test:e2e: it builds intodist-e2e, startsvite preview, runs the three files in the terminal and stops the server. Look at the final table with the time taken by each file. - A failure with a screenshot. In
booking.cy.js, change'Néctar Room'to'Nectar Room'(without the accent) in step 1. Runnpm run test:e2e: after four seconds of retries, the test fails and the screenshot of the moment of failure appears incypress/screenshots/. Restore it. - Without stable mode. Start the application without the
e2emode on the test port (npx vite --port 4173) and, in another terminal,npx cypress open. Runbooking.cy.jsseveral times: it is slower and, sooner or later, a run fails with "Could not connect to the Colmena server". That is the reason for section 9.4. - Why the language matters. Comment out the
window:before:loadhandler insupport/e2e.jsand runcatalog.cy.js: if the browser is set to Spanish or Catalan, the "Rooms" link no longer exists and the test fails. Restore it. - The real guards. Temporarily write a test that visits
/dashboard/bookingswithout signing in and checks that the path ends up being/loginwithredirectin the query: you are testing the router's realbeforeEach, which no Vitest test ran.
Common Mistakes and Tips
- Fixed waits with
cy.wait(ms). Slow when they are too long and insufficient when they are too short. End every action with an assertion about its effect and let the retries do the waiting. - Selecting by CSS classes or by structure. They break with any design change. Use
data-testto find elements and the visible text to check what is read. - Depending on the state another test left behind. Each test must be able to run on its own and in any order. Seed whatever you need with
onBeforeLoadorcy.session. - Ignoring the simulated API's randomness. A test that fails one time in ten ends up being ignored by the whole team. Build the tests in
e2emode. - Using fixed dates in the data. Time passes and the form rejects past dates. Calculate dates relative to today (
dateInDays). - Storing the result of a command in a variable (
const cards = cy.get(...)). Commands do not return elements; they are queued. Chain them, use aliases (.as) or.then. - Testing with E2E what unit tests already cover. Formats, field-by-field validations and the store's edge cases belong to Vitest. E2E tests are for journeys.
- Using
{ force: true }to make an action "pass". If the element is not actionable for Cypress, it is probably not actionable for the user either. - Exposing test hooks in production. The API's stable mode depends on a variable replaced when building in
e2emode; never on something that can be activated from the console of the published application. - Tip: write the E2E tests in interactive mode (
test:e2e:dev) and run them inrunmode before considering the work done: the latter is the one that will be used in continuous integration, against the real build.
Exercises
Exercise 1. Create cypress/e2e/session.cy.js with two tests of signing in through the interface (without cy.signIn): (a) a visitor without a session who opens /book/polen?attendees=3 ends up at /login, finds the focus in the email field and, after signing in as Laura, arrives at exactly /book/polen?attendees=3; (b) with an incorrect password, the message "Incorrect email or password." appears and the user stays at /login.
Exercise 2. In catalog.cy.js, check the catalogue's error state and the "Retry" button. Force the API failures with window.__colmenaSimulation before loading /rooms, check that the error message appears and no card does, and then make the API work again without reloading, click "Retry" and check that the five rooms appear.
Exercise 3. Invoices are for managers only (04-06). Write cypress/e2e/permissions.cy.js with two tests: as Laura (member), opening /dashboard/invoices leads to /dashboard/profile; as Marta Vidal (manager), the same address shows the invoices. Use cy.signIn with the appropriate account in each case.
Solutions
Solution 1.
// cypress/e2e/session.cy.js
describe('Signing in', () => {
it('leads to the login page and, after signing in, returns to the requested route', () => {
cy.visit('/book/polen?attendees=3')
cy.location('pathname').should('eq', '/login')
cy.location('search').should('contain', 'redirect=')
cy.get('[data-test="login-email"]').should('have.focus').type('[email protected]')
cy.get('[data-test="login-password"]').type('colmena', { log: false })
cy.get('[data-test="login-submit"]').click()
cy.location().should((location) => {
expect(location.pathname).to.eq('/book/polen')
expect(location.search).to.eq('?attendees=3')
})
})
it('shows an error with incorrect credentials', () => {
cy.visit('/login')
cy.get('[data-test="login-email"]').type('[email protected]')
cy.get('[data-test="login-password"]').type('bee')
cy.get('[data-test="login-submit"]').click()
cy.get('[data-test="login-error"]').should('have.text', 'Incorrect email or password.')
cy.location('pathname').should('eq', '/login')
})
})- The first test goes through the real global guard:
requiresSessionon the booking route, the redirect withredirect(encoded in the query),v-focuson the email field (should('have.focus')), authentication with its 600 ms delay (which the retries absorb) and thereplaceto the destination, with its own query intact. cy.location()with a function checks the path and the query at once; Cypress retries the whole function until both are met.- The second is the only test that needs to type incorrect credentials: that is why it does not use
cy.signIn. The exact text comes fromerrors.api.credentialsinen.json(07-03), throughtranslateError.
Solution 2.
// In catalog.cy.js, inside the describe
it('shows the API error and recovers with "Retry"', () => {
cy.visit('/rooms', {
onBeforeLoad(win) {
win.__colmenaSimulation = { errorProbability: 1 } // every request fails
}
})
cy.contains('Could not connect to the Colmena server').should('be.visible')
cy.get('[data-test="room-card"]').should('not.exist')
// The API works again, without reloading the page
cy.window().then((win) => {
win.__colmenaSimulation.errorProbability = 0
})
cy.contains('button', 'Retry').click()
cy.get('[data-test="room-card"]').should('have.length', 5)
})onBeforeLoaddefines the flag before the application starts, so the first catalogue request already fails. It only works because the tests run against the build ine2emode: in the published application, the flag would have no effect.cy.window().then(...)gives access to the application'swindowin the middle of the test. Assettings()is consulted on every request, changing the flag takes effect on the next one: the "Retry" one.cy.contains('button', 'Retry')uses the text because that is what the test wants to check the user sees. If this button were used in many tests, it would deserve its owndata-test.
Solution 3.
// cypress/e2e/permissions.cy.js
describe('Dashboard permissions', () => {
it('a member cannot see the invoices', () => {
cy.signIn() // Laura Gómez, member
cy.visit('/dashboard/invoices')
cy.location('pathname').should('eq', '/dashboard/profile')
})
it('a manager can see them', () => {
cy.signIn('[email protected]')
cy.visit('/dashboard/invoices')
cy.location('pathname').should('eq', '/dashboard/invoices')
cy.contains('Invoices')
})
})- Two accounts, two saved sessions: the
cy.sessionidincludes the email, so Laura's session and Marta's are saved separately and each one is restored when it is requested. - The first test checks the guard based on
meta.rolein the router's realbeforeEach; the second, that the guard lets through someone who does have the role. Remember the warning from 04-06: this checks the user experience, not security, which is the server's job.
Conclusion
End-to-end tests check the complete application in a real browser, as a person uses it, and they cover what no unit test sees: main.js, the router's real guards, the lazy loading of views and languages, the browser's storage and the real sequence of screens. They are the most expensive in the pyramid, so they are reserved for critical journeys. Cypress is configured in cypress.config.js with baseUrl and the tests in cypress/e2e/*.cy.js; start-server-and-test starts the application and the tests with a single command, in interactive mode (cypress open) while they are being written and without an interface (cypress run) against the real build. The tests visit pages with cy.visit, find elements with cy.get and cy.contains through data-test attributes (which we have added to the header, the login page, the card, the spec sheet, the form and "My bookings"), interact with type, click, select and check, check with should and cy.location, and rely on automatic retries instead of fixed waits. The state is controlled by seeding localStorage and sessionStorage in onBeforeLoad, setting the default language in support/e2e.js and building in e2e mode, which activates in src/api/simulation.js a simulation with no delay or random failures (with the window.__colmenaSimulation hook for forcing errors, which only exists in that build). The cy.signIn() command, with cy.session, signs in only once per account, and with all of this we have tested Colmena's complete journey (session, catalogue filtered by URL, spec sheet, booking, "My bookings" and cancellation) and the language change, with screenshots and videos for understanding failures and Playwright as a known alternative.
With this module, Colmena Bookings is now covered by tests at every level: Vitest and Vue Test Utils keep watch in seconds over functions, components, views, stores, plugins and composables, and Cypress checks in a real browser that a member can sign in, find a room, book it and cancel it in any of its three languages. That safety net changes the way you work: you no longer need to go through every "Try it" by hand to dare to modify the code, and it is precisely now that it makes sense to tackle the advanced techniques that require reorganising it. While writing the tests you will have noticed logic that repeats from one view to another: the catalogue filters synchronised with the URL, the checks on a room's availability, the pattern of loading data with its loading and error states. Extracting it into reusable functions, testing it just once with withHost and then checking with npm test and npm run test:e2e that nothing has broken is the first step of the next module, which begins with The Vue 3 Composition API in Depth: Composables and Logic Reuse.
Vue.js Course
Module 1: Introduction to Vue.js
- What Is Vue.js?
- Setting Up the Development Environment
- Creating Your First Vue Application
- Understanding the Vue Instance: Application, Components and Lifecycle
- Options API and Composition API: Two Ways to Write Components
Module 2: Vue.js Basics
- Template Syntax
- Reactivity: ref and reactive
- Data Binding
- Event Handling
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Forms with v-model
Module 3: Vue.js Components
- Introduction to Components
- Props and Custom Events
- v-model on Your Own Components
- Slots
- Template Refs and Fallthrough Attributes
- Dynamic and Async Components
- Component Communication
Module 4: Vue Router
- Introduction to Vue Router
- Setting Up Vue Router
- Dynamic Routes
- Nested Routes
- Programmatic Navigation and Query Parameters
- Navigation Guards
Module 5: State Management with Vuex and Pinia
- Introduction to Vuex
- State, Getters, Mutations and Actions
- Vuex Modules
- Using Vuex in Components
- Advanced Vuex Patterns
- Pinia: The Recommended State Management for Vue 3
- Migrating from Vuex to Pinia
Module 6: Vue.js Directives
Module 7: Vue.js Plugins
Module 8: Testing in Vue.js
- Unit Testing with Vue Test Utils and Vitest
- Mocking Dependencies
- Testing Composables and Stores
- End-to-End Testing with Cypress
Module 9: Advanced Vue.js Concepts
- The Vue 3 Composition API in Depth: Composables and Logic Reuse
- Vue with TypeScript
- Render Functions and JSX
- Transitions and Animations
- Teleport, Suspense and Error Handling
- Server-Side Rendering (SSR) with Nuxt
- Performance Optimization
