Exit course
Chapter 2 of 11 Beginner 6 min read 2 quick checks Updated

Install Cypress and Run a First Spec

Watch this chapter Starts at 1:14 in the 9:03 course video.
On this page
  1. Create the project
  2. Let Cypress scaffold the files
  3. Write the first spec
  4. Run it two ways
  5. Add scripts to package.json
  6. Where to go from here

In this chapter you create a project, let Cypress scaffold its files, write a first spec against a real todo app and run it in the two modes you will use every day.

Create the project#

Cypress is an npm package. Make an empty folder, give it a package.json and install a pinned version:

mkdir cypress-course && cd cypress-course
npm init -y
npm install --save-dev cypress@14.2.0

The npm package is small; the first install also downloads the Cypress app itself (a few hundred megabytes) into a shared cache folder outside your project, so the next project on the same machine installs quickly. Check that it works:

npx cypress verify

Pinning the exact version matters more with Cypress than with most libraries. A plain npm install cypress gives you the newest major release, and chapter 8 runs this suite on TestingBot with cypressVersion set to 14.2.0. Running the same version locally and in the cloud keeps "works on my machine" out of the picture.

Let Cypress scaffold the files#

Open the Cypress app:

npx cypress open

The Launchpad asks which kind of testing you want. Pick E2E Testing. Cypress then creates the files it needs and shows you what it wrote:

cypress-course/
  cypress.config.js
  cypress/
    fixtures/example.json
    support/commands.js
    support/e2e.js
  • cypress.config.js is the configuration file. Chapter 6 covers it properly.
  • cypress/support/e2e.js runs before every spec file. It imports commands.js, where custom commands go (chapter 5).
  • cypress/fixtures/ holds test data files you load with cy.fixture() or use as stubbed responses (chapter 4).

Choose a browser (Chrome if it is installed, or the bundled Electron) and Cypress offers to create an example spec. Close the app for now; you will write your own.

Open cypress.config.js and add a baseUrl, so specs can visit relative paths:

const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    baseUrl: 'https://example.cypress.io',
  },
})

Write the first spec#

Cypress looks for end-to-end specs matching cypress/e2e/**/*.cy.{js,jsx,ts,tsx}. Create cypress/e2e/todo.cy.js:

describe('todo app', () => {
  beforeEach(() => {
    cy.visit('/todo')
  })

  it('shows two todos by default', () => {
    cy.get('.todo-list li').should('have.length', 2)
  })

  it('adds a new todo', () => {
    cy.get('[data-test=new-todo]').type('Buy milk{enter}')

    cy.get('.todo-list li')
      .should('have.length', 3)
      .last()
      .should('have.text', 'Buy milk')
  })
})

What is going on:

  • describe, it and beforeEach come from Mocha, which Cypress bundles. There is nothing to import.
  • cy.visit('/todo') loads https://example.cypress.io/todo, because the path is resolved against baseUrl.
  • cy.get() finds elements with a CSS selector. [data-test=new-todo] targets an attribute that exists only for tests, which chapter 2 explains.
  • .type('Buy milk{enter}') types text; {enter} is a special key sequence that presses Enter.
  • .should(...) is an assertion that retries: if the list has two items when Cypress first looks, it keeps looking until it has three or the timeout runs out.
  • .last() narrows the subject to the last list item, and the second .should checks its text.

There is no await anywhere, and no variable holds an element. Every cy. call adds a command to a queue that Cypress runs after it returns. Chapter 2 is about exactly that.

The second test runs after the first one, which also visited the page. Why does it still start with two todos rather than leftovers from the first test?

With test isolation (the default since Cypress 12), every test starts from a blank page with empty cookies and storage. The todo app keeps its list in local storage, so the second test sees the default two items again. beforeEach only visits; it does not clean anything up.

Run it two ways#

Interactively, while you write tests:

npx cypress open

Pick E2E Testing, a browser, and click todo.cy.js. The spec runs in the browser you chose, and the command log on the left lists every command. Hover over a command to see the page as it was at that moment; that "time travel" is the main debugging tool of chapter 9. The runner watches your files, so saving the spec reruns it.

Headlessly, the way CI runs it:

npx cypress run

This runs every spec in the bundled Electron browser without a window and prints a summary table. Some flags you will use constantly:

npx cypress run --spec cypress/e2e/todo.cy.js   # one spec (globs work too)
npx cypress run --browser chrome                # an installed browser: chrome, firefox, edge
npx cypress run --headed                        # show the browser window

cypress run exits with the number of failed tests as its exit code (0 when everything passed), so a CI job fails when a test does.

A teammate added a spec called cypress/e2e/login.spec.js. npx cypress run does not pick it up. Why?

The default specPattern is cypress/e2e/**/*.cy.{js,jsx,ts,tsx}. Rename the file to login.cy.js, or change specPattern in the config if your team prefers another naming scheme.

Add scripts to package.json#

Nobody remembers flags. Add two scripts:

"scripts": {
  "cy:open": "cypress open",
  "cy:run": "cypress run"
}

and run npm run cy:run. Chapter 8 adds a third one for the cloud.

Where to go from here#

You now have a project that runs. The TestingBot Cypress tutorial in our documentation is a shorter version of this chapter that goes straight to the cloud; this course takes the longer route because the next five chapters decide whether your suite stays fast and stable as it grows. If your team writes scenarios in Gherkin, our article on Cypress and Cucumber shows how to add a preprocessor on top of the same project.