LogoLogo
  • FAC Curriculum
  • archive
    • Node & npm introduction
    • developer
      • Programming Paradigms
    • handbook
      • Asking for help
      • Coaching groups
      • Code review
      • Course rules
      • Debugging
      • Employment schedule and material delivered in FAC20
      • GitHub Workflow
      • Glossary or terms
      • Presentation Guidance
      • Equality, Diversity and Inclusion
      • Installation guide
      • Learning circles
      • Mentoring guidance
      • What to expect from your mentors
      • One-day projects
      • Pair programming
      • Portfolio
      • Questions for problem solving
      • Progress Logs
      • Final project report
      • Managing software projects
      • Project Presentations
      • Project roles
      • Projects
      • Retrospectives
      • Role Circles
      • Safeguarding policy
      • Technical Spikes
      • System requirements
      • Tech for Better
      • User Manuals
      • Wellbeing Support
      • project-docs
        • What makes a mentor?
        • Product Handover
        • Sprint Planning
        • Tech for Better Presentations
        • User Research & Usability Testing
    • foundation
      • full-stack
        • Learning Outcomes
        • project
      • testing
        • project
        • spikes
  • docs
    • Contributing to the curriculum
    • Curriculum intent
    • Curriculum process
  • src
    • About our curriculum
    • course
      • Code of Conduct
      • Docker
      • .NET and Umbraco
      • Getting started
      • Founders and Coders coursebook
      • KSB's
      • Mini projects
      • Revision checklist
      • Svelte
      • TypeScript
      • handbook
        • Software Developer Handbook
        • Software Foundation Handbook
      • precourse
        • Before you start the course
        • Installation List
      • syllabus
        • developer
          • app
            • learning-outcomes
            • project
            • schedule
            • spikes
          • introduction
            • learning-outcomes
            • project
            • resources
            • schedule
          • week00-pre-course
            • We'd like you to spend some time before starting the course working on useful fundamentals.
            • spikes
          • week01-project01-basics
            • Employability introduction
            • Homework
            • learning-outcomes
            • Week of September 9th
            • project
            • resources
            • schedule
            • spikes
          • week02-project02-chatbot
            • employability
            • Homework
            • learning-outcomes
            • Week of September 16th
            • project
            • resources
            • schedule
            • spikes
          • week03-project03-server
            • Learning Outcomes
            • Week of September 23th
            • The Amazin' Quizzer API Backend
            • resources
            • schedule
          • week04-project03-frontend
            • learning-outcomes
            • Week of September 30th
            • UI for Quizzer App
            • resources
            • schedule
          • week05-project03-test-deploy
            • Testing and deployment
            • Week of October 7th
            • project
            • resources
            • schedule
          • week06-project04-databases
            • learning-outcomes
            • Week of October 14th
            • project
            • Databases
            • schedule
          • week07-project04-authentication
            • Learning Outcomes
            • Week of October 21st
            • project
            • resources
            • schedule
          • week08-project04-test-deploy
            • Learning Outcomes
            • Week of October 28th
            • project
            • resources
            • schedule
          • week09-reading-week
            • Learning Outcomes
            • overview
            • Project
            • Resources
            • schedule
          • week10-project05-DOTNET-intro
            • Learning Outcomes
            • overview
            • project
            • Resources
            • schedule
          • week11-project05-DOTNET-testing
            • Testing and deployment
            • Week of November 18th
            • project
            • Resources
            • schedule
          • week12-project05-DOTNET-deploy
            • Learning Outcomes
            • Week of November 25th
            • project
            • Resources
            • schedule
            • Spikes
          • week13-TFB-design
            • Learning Outcomes
            • overview
            • Project
            • Resources
            • schedule
            • Design Week Spikes
          • week14-TFB-build
            • Learning Outcomes
            • overview
            • Project
            • DevOps Resources
            • schedule
            • Spikes
          • week15-TFB-build
            • Learning Outcomes
            • overview
            • Project
            • Resources
            • schedule
            • Spikes
          • projects
            • in-house-design
              • Learning Outcomes
              • Project
              • Resources
              • schedule
              • Design Week Spikes
        • foundation
          • Obsolete-full-stack
            • project
          • post-course
            • Homework
            • schedule
        • portfolio
          • fruit-shop
            • learning-outcomes
            • project
            • resources
          • game
            • learning-outcomes
            • project
            • resources
          • hobby-page
            • learning-outcomes
            • project
            • resources
          • movie-data
            • learning-outcomes
            • project
            • resources
          • project-gallery
            • learning-outcomes
            • project
            • resources
          • website
            • learning-outcomes
            • project
            • JavaScript
        • tfb
          • week 1
            • Introduction (45 minutes)
            • Further reading
          • week 10
            • content
            • resources
          • week 11
            • What will we be doing this week?
            • resources
          • week 12
            • What will we be doing this week?
            • Further reading
          • week 2
            • Discover (90 minutes)
            • resources
          • week 3
            • content
            • resources
          • week 4
            • Mapping the user journey (90 minutes)
            • resources
          • week 5
            • Figma Workshop 1 (90 minutes)
            • Further reading
          • week 6
            • Figma Workshop 2 (90 minutes)
            • resources
          • week 7
            • Product pitches & Selection (90 minutes)
            • resources
          • week 8
            • content
            • resources
          • week 9
            • content
            • resources
    • learn
      • DOTNET
        • Introduction to .NET
      • auth
        • Authenticating web apps
      • database
        • Persisting data with SQLite and Node
      • dotnet-two
        • Dependency injections and interfaces in .NET
      • form-validation
        • Form validation
      • react
        • Building client-side apps with React
      • server
        • HTTP servers with Node & Express
      • typescript
        • TypeScript
    • mentoring
      • design-week
        • Analysis Workshop
        • Code planning
        • Definition Workshop
        • Discovery Workshop
        • Figma introduction
        • Usability testing
        • User Research
    • resources
      • http
        • introduction
    • workshops
      • cookie-auth
        • index
      • creating-promises
        • index
      • css-layout
        • index
      • cypress-testing
        • index
      • database-testing
        • index
      • dev-tooling
        • Developer tooling
      • dom-challenge
        • index
      • dom-rendering
        • index
      • es-modules
        • index
      • express-middleware
        • Express middleware
      • first-class-functions
        • index
      • form-validation
        • index
      • functions-callbacks-async
        • Functions, callbacks, & async JavaScript
      • git-intro
        • Introduction to Git
      • git-terminal
        • Using Git in the terminal
      • git-workflow
        • Git workflow
      • github-projects
        • GitHub Projects Workflow Workshop
      • heroku-sql-challenge
        • index
      • html-forms
        • index
      • learn-a11y
        • index
        • starter-files
          • solution
            • Accessibility solution explanation
      • learn-fetch
        • index
      • learn-integration-testing
        • index
      • learn-testing
        • Learn testing in JavaScript
      • learn-unit-testing
        • index
      • node-error-handling
        • Node error-handling
      • node-express-server
        • Node and Express HTTP server
      • node-npm-intro
        • Node & npm introduction
      • node-postgres
        • Learn Postgres with Node
      • node-scripting-challenge
        • index
      • password-security
        • index
      • promise-practice
        • index
      • react-components
        • React components
      • react-fetch
        • index
      • react-forms
        • React forms
      • react-refactor-classes
        • index
      • react-state-effects
        • React state & effects
      • real-world-fetch
        • index
      • scope-challenge
        • Scope debugging challenge
      • semantic-html
        • index
      • server-side-forms
        • Server-side forms
      • session-auth
        • Session authentication
      • sql-intro
        • index
      • tdd-array-methods
        • index
Powered by GitBook
On this page
  • Setup
  • Your first Cypress test
  • Cypress commands
  • Workshop
  • Quick setup
  • Requirements for your server
  • Stretch goal
Export as PDF
  1. src
  2. workshops
  3. cypress-testing

index

Learn how to use Cypress to test your app in a real browser

Cypress is a tool for automatically running your tests in a real web browser. Lots of testing libraries run using Node in your terminal. This means they struggle to test real user interactions with the DOM (since Node doesn't have one).

You can test in the browser by manually including test functions in a script tag on the page. However this isn't ideal as you have to remember to remove them from your production deployment (or all your users can see your test results in the console).

Cypress solves this problem by letting you write separate test files, then injecting them into a real browser. Since it automatically controls a browser you can see your tests running in in real time.

Setup

First we need to create a new directory and initialise it so we can install modules:

mkdir cypress-testing
cd cypress-testing
npm init -y

Once you're inside your new directory and have generated a package.json file you can install Cypress as a dev dependency:

npm install -D cypress

Cypress can take a while to install the first time, so be patient. Once it's finished open your package.json and edit the "test" script to this command:

{
  "scripts": {
    "test": "cypress open"
  }
}

Run npm run test in your terminal, and you should see the Cypress app start up. The window will show a bunch of example tests—don't worry about these for now.

The first time you run Cypress it automatically creates some files. You should see a cypress.json file and a cypress/ directory full of examples. The JSON file is used to configure Cypress—you can leave it empty for now.

Now you're ready to write your first test.

Your first Cypress test

By default Cypress looks in the cypress/integration/ directory for test files. It will run anything inside this folder. You can delete the auto-generated example/ folder, since we're going to start from scratch.

Create a new file called practice-tests.js. You should see this file show up in the Cypress app under "Integration tests".

You can click the file name to run it with Cypress. This should open up a browser with a "test sidebar" on the left. Since we didn't actually write any tests yet it'll say "No tests found".

Let's add a simple test to the file:

it("can run a test", () => {
  assert.equal(1, 1);
});

If you save your test file Cypress should automatically re-run the test. It will now find the test and show the result in the sidebar.

This is a fine way to write simple unit tests, but Cypress is much more powerful. Let's test a real web page.

Add a new test function:

it("can navigate pages", () => {
  cy.visit("https://example.cypress.io/");
});

We're using the global cy object to run a "command". cy.visit tells Cypress to load a URL in the browser and wait for the page to load.

You should see the test re-run in your Cypress browser. The right side should load Cypress' example app (called "Kitchen Sink").

Let's add a command to find an element on the page:

it("can navigate pages", () => {
  cy.visit("https://example.cypress.io/");
  cy.contains("within");
});

cy.contains will search the text content of all elements until it finds a match. If you click this test in the sidebar you should see the "Test body" table. Hover the contains command and the browser on the right will update to highlight the element it found.

If a Cypress command fails it will cause the test to fail. For example change your test to search for an element containing "zzzzzz". You should see an error message in the sidebar.

Now let's interact with this element in our test:

it("can navigate pages", () => {
  cy.visit("https://example.cypress.io/");
  cy.contains("within").click();
});

This will tell Cypress to click the link. You should see the test re-run, and the browser navigate to the "Querying" page.

Finally we can make an assertion about the new page to verify that we got to the right place:

it("can navigate pages", () => {
  cy.visit("https://example.cypress.io/");
  cy.contains("within").click();
  cy.url().should("include", "/commands/querying");
});

This syntax is a little strange at first, but it's supposed to read like a sentence. The cy.url method retrieves the current URL. The .should method creates an assertion. Here we are checking that the URL includes the sub-string "/commands/querying".

That's it—we've created a full integration test with Cypress. It's important to note that we aren't limited to a single set of tasks in a test. We can keep adding more commands in here until we're satisfied.

Cypress commands

cy.get("#signup-form").find("input[name='email']").type("my-email@test.com");
cy.get("#signup-form").submit();

Here we're getting the sign up form, finding the email input within it, then typing an email into that input. Finally we get the form again and submit it.

cy.get takes a CSS selector to find an element, just like querySelector in the DOM. .find works the same way, but it searches the children of an element. .type simulates typing text via the keyboard. .submit triggers a form submission.

Workshop

You're going to use Cypress to build a server TDD-style. That means write a failing test for each feature first, then implement that feature to make the test pass.

Quick setup

  1. Create a server.js file

  2. npm install express

  3. npm install -D nodemon (for auto-restarting the server)

  4. Add a "dev" npm script of: nodemon server.js

Write your Express server in server.js. Write your tests in cypress/integration/.

Requirements for your server

  • / page with a title of "Welcome to my site"

  • / page has working links to /about and /sign-up

  • /about page with a title of "About this site"

  • /sign-up page with a form containing email/password inputs

  • /welcome page with a title of "Thanks for joining"

  • /sign-up page redirects to /welcome after form submission (don't worry about actually using the submitted data)

Stretch goal

Previouscypress-testingNextdatabase-testing

Last updated 3 years ago

The Cypress app showing a single test

Cypress uses a global it function to define tests. This works just like the test function we wrote in the workshop—it just has a different name.

My browser running our first test

A failed test in the sidebar

You can find a full set of available commands at . Here's a quick example with a few new ones that will useful:

If you have spare time go back to the . Use Cypress to write tests for your solution to verify that it works correctly

intro to testing
https://example.cypress.io/
server-side forms workshop
The Cypress app window showing just our new test file: practice-tests.js
My Edge browser being controlled by Cypress. It shows our passing test in the sidebar on the left.
Cypress has highlighted the failing test in red in the sidebar. It includes a message telling us that it couldn't find the expected text content after a 4 second wait.