lecture 2 of 170 completed

Installing Cypress and the shape of a project

What the install actually creates, what each folder is for, and the two config mistakes that cost beginners an afternoon.

On this site you write Cypress tests without installing anything. On a real job you will install it on day one, and the folder it creates will look like clutter until someone explains it. Here is that explanation.

Cypress installs like any other JavaScript package. From inside your project:

npm install cypress --save-dev

--save-dev means "this is a tool for developing, not part of the shipped app". Tests never go to production, so they belong here.

Then open it once:

npx cypress open

npx runs a tool you installed locally. The first run creates the folder structure and opens the interactive runner, a window where you pick a spec and watch it execute.

Here is what appears, and what each part is for.

cypress/
  e2e/          your test files live here
  fixtures/     static test data, usually JSON
  support/
    e2e.js      runs before every spec file
    commands.js your own reusable commands
cypress.config.js

cypress/e2e holds your specs. A spec is one test file, named like login.cy.js. The .cy. part is what tells Cypress to run it.

cypress/fixtures holds fixed data files. A JSON file of sample contacts, for example, that a test can load instead of typing the data inline.

cypress/support/e2e.js runs before every single spec. Global setup goes here.

cypress/support/commands.js is where you add your own commands, so cy.login() can become a thing your team writes. There is a lecture on this later in the track.

cypress.config.js is the project's settings file. The one setting you will set on day one is the address of your app:

const { defineConfig } = require('cypress');

module.exports = defineConfig({
  e2e: {
    baseUrl: 'http://localhost:3000',
  },
});

With baseUrl set, cy.visit('/login') goes to http://localhost:3000/login. Without it you would write the full address in every test, and changing environments would mean editing every file.

Two mistakes worth avoiding, both of which I have watched people lose hours to.

Your app has to be running. Cypress does not start your application. It opens a browser and points it at an address. If nothing is serving that address, every test fails immediately with a connection error, and the error looks alarming rather than obvious. Start your app first, in a separate terminal.

cypress open and cypress run are different. open gives you the interactive window for writing tests. run executes everything headlessly in the terminal and is what a build server uses. A suite that passes in open can fail in run, usually because of timing, and that surprise is covered later in the track.

Remember this: install it, point baseUrl at your running app, and put specs in cypress/e2e.

Reference: Installing Cypress.