• Home
  • Public Speaking
  • Travel
Let's start a journey with Cypress from scratch

Cypress: JavaScript End to End Testing Framework

First Steps

Prepare the environment

Cypress is a framework running with JavaScript. It can be downloaded from the official site. NPM is the package manager in JS environment. We will use it to manage JS dependencies (cypress as well). Any IDE can be used to develop test framework, A compatible one like VS Code is recommended though.


Let's Create our Project

After creating an empty directory, run the command

npm -i init

After answering the init command questions, a package.json file will be created in the project:


Now let's import Cypress into our project:

npm install cypress --save-dev

Since we add the dev-dev parameter, we will see the dependency in the package.json file from now on. Any time, the dependencies can be updated with "npm update" command

Execute Cypress

We can start the test runner from terminal with the command:

node_modules/.bin/cypress open

We are ready to create our first spec file. We can define suites ("describe") including numerous tests ("it") in this spec file. On the test runner, when we select the test, it will run on the chosen browser:


Instead of cypress open command, if we run cypress run command, it executes all tests under integration folder. But the difference from execution on Test Runner is, this time they will be executed in headless mode.

"node_modules/.bin/cypress run" or "npx cypress run"


If we want to run a specific spec file instead of the whole suite,

"npm run cy:run -- --spec "cypress/integration/MyTest.js""

Additional parameters can be attached like,

--headed --browser chrome

The configuration can be modified either from the settings menu or cypress.json file

Test Code

Cypress element recognition is based on css selectors. After locators are defined, the main cypress commands will be executed with assertions.


Locators

parent tagname.classname {i.e: input.search-keyword}
parent tagname[attribute=value] {i.e: input[type=’search’]}

We can narrow the selection criteria with element attributes:
  • :contains("Text")
  • :visible
  • :nth-child(N)


Commands

Main cypress commands are:
  • cy.visit, cy.go(‘back’), cy.url()
  • cy.wait,
  • cy.log, console.log,
  • cy.wrap,
  • cy.get, cy.contains
    • .then
    • .find
      • .eq
      • .each
    • .clear, .type,
    • .click,
    • .check, .uncheck, .select
    • .as
    • .invoke
      • (‘removeAttr’,’target’)
      • (‘show’)
    • .next
  • cy.on(Events,(str)=> {})
    • ‘Window:alert’

Element Attributes can be read such as:
  • .text()
  • .length
  • .prop


Assertions

Mocha assertions are used to check expected results. Some of them are:


A Sample test would look like: