Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 35 ยท Getting Started

Your First Cypress Test

Install Cypress, open the runner, learn the folder layout and write your first test with cy.visit, cy.get, cy.contains and should, with retrying assertions.

Cypress is the quickest tool to try if you like seeing a test run. You install one package, open a window, and watch your test click through your app while a log of every command appears beside it. This lesson walks through the real setup and your first test, then uses a runnable stand-in to show the single most important idea inside Cypress: commands and assertions retry until they pass or time out.

Cypress needs Node.js, a desktop or CI machine and your running application, so the commands and files below are read-only. The runnable example at the end is a small mini runner that reproduces the describe/it structure and the retry behavior; it is not Cypress itself.

Install and open

In a project that already has a package.json:

Terminal
# read-only: run these in your own project
npm install --save-dev cypress
npx cypress open

npx cypress open starts the interactive app. On the first run it creates a configuration file and a folder of example files, and asks you to choose E2E Testing. You then pick a browser and start a spec. Every time you save the spec, Cypress runs it again, which makes it pleasant to write tests while you develop.

For a non-interactive run, such as on a build server, use:

Terminal
# read-only
npx cypress run
npx cypress run --browser chrome
npx cypress run --spec "cypress/e2e/home.cy.js"

cypress run is headless by default, runs every spec file and prints a summary. It can also record videos and screenshots of failures.

The folder layout

After setup, a project looks like this:

TEXT
my-app/
  cypress.config.js
  cypress/
    e2e/             <- your test files: *.cy.js (or .cy.ts)
    fixtures/        <- static test data, such as JSON files
    support/
      e2e.js         <- code that loads before every spec
      commands.js    <- your custom commands

The configuration file is short at first:

JavaScript
// cypress.config.js (read-only)
const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    baseUrl: 'http://localhost:3000',
    setupNodeEvents(on, config) {
      // plugins and Node-side tasks go here
    },
  },
})

Setting baseUrl is worth doing straight away. With it, cy.visit('/login') means http://localhost:3000/login, and the same tests can run against another environment by changing one value (Configuration and Environments).

Your first test

Create cypress/e2e/home.cy.js. Suppose your home page has a heading, a search box with the attribute data-cy="search", and a list of results.

JavaScript
// cypress/e2e/home.cy.js (read-only)
describe('home page', () => {
  it('shows the heading', () => {
    cy.visit('/')
    cy.get('h1').should('contain.text', 'Learn to code')
  })

  it('filters lessons while typing', () => {
    cy.visit('/')
    cy.get('[data-cy=search]').type('closures')
    cy.get('[data-cy=result]').should('have.length', 1)
    cy.contains('[data-cy=result]', 'Closures').should('be.visible')
  })
})

Cypress ships with its test structure built in, using the style of Mocha: describe groups related tests and it defines one test. Chai and its Cypress extensions provide assertions.

The commands you will use first

Command What it does
cy.visit(url) Loads a page. Relative URLs use baseUrl.
cy.get(selector) Finds elements matching a CSS selector.
cy.contains(text) Finds an element by the text it shows. With a selector first, it narrows the search.
.type(text) Types into an input.
.click() Clicks an element.
.should(chainer, value) Asserts something about the subject, and retries.

Commands chain: each one acts on what the previous one found. cy.get('[data-cy=search]').type('closures') means "find the search box, then type into it". The thing being passed along is called the subject.

Assertions with should

.should() takes a Chai chainer as a string. Common ones:

JavaScript
// read-only
cy.get('h1').should('be.visible')
cy.get('h1').should('have.text', 'Welcome')
cy.get('li').should('have.length', 3)
cy.get('[data-cy=submit]').should('be.disabled')
cy.get('input').should('have.value', '[email protected]')
cy.get('.error').should('not.exist')

You can pass a callback for custom checks, and chain several checks with .and():

JavaScript
// read-only
cy.get('[data-cy=price]')
  .should('be.visible')
  .and('contain.text', '$')

Running and reading the result

When a command or assertion cannot succeed within the timeout, Cypress fails the test and says what it was waiting for, for example that it timed out retrying while expecting an element to exist. The default timeout for most commands is four seconds. In the interactive runner, you can click each command in the log to see a snapshot of the page at that moment, a feature known as time travel (Debugging Failing Tests).

flowchart LR
  A["cy.get('h1')"] --> B["should('contain.text', 'Learn')"]
  B -->|"fails"| C{"Time left?"}
  C -->|"yes"| A
  C -->|"no"| D["Test fails with the last error"]
  B -->|"passes"| E["Next command"]

A retrying command: when the assertion fails, Cypress queries again until it passes or the timeout ends.

This loop is the secret behind reliable tests. You never write "wait 2 seconds". You state what should be true, and Cypress keeps checking.

Building a mini runner

You cannot run Cypress here, but you can build the two ideas it rests on: a runner that collects describe and it and reports results, and a should that retries. The stand-in below uses a virtual clock, so it runs instantly and gives the same output every time. The fake page shows its heading only after 300 virtual milliseconds, like a page that is still loading.

Node.js A mini runner with retrying assertions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output closely. The first test passes only after several attempts, because the heading was not there at first, and the report says how many tries it needed. The last test fails after the whole 4,000 ms budget and the error shows the last thing it saw, just like Cypress's own messages. Real Cypress retries queries such as get together with the assertion that follows them, which is why the stand-in re-queries the page inside every attempt.

Habits to build from day one

  • Prefer data-cy (or similar) attributes in selectors, as covered in Selecting Elements in Cypress and Writing Selectors That Do Not Break.
  • Never add fixed waits like cy.wait(2000) to "fix" timing. Assert on what you are waiting for.
  • Keep each test independent. Visit the page you need at the start of the test.
  • Set baseUrl so paths stay short and environments stay swappable.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which command opens the interactive Cypress runner?

    npx cypress open starts the interactive app; npx cypress run runs specs headlessly, for example on a build server.
  2. 2. Where do Cypress end-to-end spec files normally live?

    End-to-end specs go in cypress/e2e by default and use the .cy.js or .cy.ts extension.
  3. 3. What does cy.get('h1').should('contain.text', 'Welcome') do if the heading says 'Loading' at first and 'Welcome' after a second?

    Cypress retries the query and the assertion together until they pass or the timeout (four seconds by default) is over.
  4. 4. Why set baseUrl in cypress.config.js?

    With baseUrl, relative visits resolve against it, so the same tests can target local, staging or other environments by changing one value.

Summary

  • Install with npm install --save-dev cypress; open the runner with npx cypress open and run headless with npx cypress run.
  • Specs live in cypress/e2e/*.cy.js; fixtures and support files have their own folders; cypress.config.js holds settings like baseUrl.
  • describe and it structure tests; cy.visit, cy.get, cy.contains, .type, .click and .should are the first commands to learn.
  • Commands chain by passing a subject along, and assertions retry until they pass or time out.
  • Do not use fixed waits; assert on what should become true.
  • The mini runner is a stand-in that shows the structure and the retry loop, not the real Cypress code.

Next: Your First Playwright Test