Cypress automating tool

From A Technological Wiki
Revision as of 18:51, 19 October 2025 by Maintenance script (talk | contribs) (Added category IT Quality assurance team)
Jump to navigation Jump to search

Cypress is an end-to-end testing framework designed for modern web applications for enhancing the efficiency, reliability, and user experience of automated functional testing. Unlike traditional testing tools that operate outside the browser, Cypress runs directly inside it, enabling more consistent real-time interactions and observations. Key benefits for automated functional testing include:

  • Real-time Feedback: Instantly see test results and debug directly in the browser.
  • Automatic Waiting: Cypress auto-waits for elements, reducing flakiness.
  • Time Travel: Snapshot the DOM at different stages to understand test progress.
  • Parallel Execution: Speeds up test runs by distributing tests across machines.
  • Rich Ecosystem: Comes with mocking, stubbing, and network interception capabilities.
  • Comprehensive Documentation: Simplifies learning and adoption.
  • Cross-browser Testing: Ensures app compatibility across different browsers.

Installing Cypress

  • Install node. In our case we should have it as a docker image

  • generating package.json

    npm init
  • install cypress

    npm install cypress --save-dev
    ./node_modules/.bin/cypress install
  • open Cypress GUI

    node_modules/.bin/cypress open
  • Select E2E Testing, it will create cypress folder and cypress.config.js

  • On browser, select Specs and Create Examples

    • click Advanced Examples - Actions for and example

  • run tests from CLI

    node_modules/.bin/cypress run
    --spec e2e/my_tests/smoke_tests.cy.js
    --config-file cypress.config.js
    --config video=true

Extra cypress configurations (--config): https://docs.cypress.io/guides/references/configuration

To display browser during CLI run use --headed

Coding

hello world

  • Create a folder inside cypress/e2e for our context
  • create hello_world.cy.js file with:
// defines test suite
describe('Smoke Tests', {optional_config_keys: value}, () => {
    // defines test case/s
    it('Sample test', () => {
        // logs a message
        cy.debug('Console message');
    })
})

suites and test configurations

describe(
    'Tests Suite',
    {
        viewportWidth: 1024,
        viewportHeight: 700,
        env: {
            DEMO: true,
            API: 'http://localhost:9000',
        }
    },
    () => {
        cy.log(cy.config(viewportWidth));
        cy.log(cy.env(DEMO));
    }
)

They can be accessed with cy.config(var) or cy.env(var)

Commands

Commands can be concatenated with .

Browser commands

cy.visit(url); // Load a page
cy.reload(); // refresh page
cy.go("back/forward"); // clicks browser button
cy.url() | .window() | .title(); // prints this info

elements selector

"CSS and Path Checker" and "Relative Xpath" browser extension is a good help

cy.get(); // gets an element. Use CSS selectors  (#, ., [att=value], etc), Xpath
[...].as(alias); // asign an alias to the selection and later use .get(@alias)
cy.contains(); // element contains a literal Text (regular expressions allowed)
cy.first() | last | next | prev | parents | children | siblings | find

elements actions

cy.type(); // fill a field
// with {} we can specify a key. Example .type({enter});
cy.clear(); // removes text
cy.click() | dblclick | rightclick; // triggers mouse click on element
// we can pass {force: true} if element is not visible
// can call it with coordinates: .click(x,y)
cy.check() | uncheck; // un/checks a radio/checkbox
cy.focus() | blur | submit | hover | select
cy.trigger(event); // trigger any DOM event

assertions

cy.should(status, value);

statuses:

cy.get('#header a') // yields the element
  .should('have.attr', 'href') // yields the "href" attribute
  .and('equal', '/users')

hooks

before(() => {}); // runs once before all tests
beforeEach(() => {}); // runs before every test
afterEach(() => {}); // runs after each test
after(() => {}); // runs once all tests are done

If they are inside a block (describe()), it only applies to them

Exceptions

Cypress.on('uncaught:exception', (err, runnable) => { return false });

utilities

cy.wait(ms); // sleep
cy.pause(); // stops the test
cy.screenshot(); // takes screenshot
cy.log(); // print message
cy.debug(); // print to browser console
cy.fixture(file); .as(alias); // loads a fixture
import user from './fixtures/file.json'; // another way
// example
cy.fixture('user').then((userFixture) => {
  expect(user, 'the same data').to.deep.equal(userFixture)
})
[...].then(); // work with yeilded subject
// hide XHR requests: on /cypress/support/e2e.js add:
// Hide fetch/XHR requests
const app = window.top;
if (!app.document.head.querySelector('[data-hide-command-log-request]')) {
  const style = app.document.createElement('style');
  style.innerHTML =
    '.command-name-request, .command-name-xhr { display: none }';
  style.setAttribute('data-hide-command-log-request', '');

  app.document.head.appendChild(style);
}
it.only(); // runs only this test of the suite
cy.wrap(); // yield (passes) to cypress an object

cy.wrap({ name: 'Jane Lane' });
const getName = () => {return 'Jane Lane'}; cy.wrap({ name: getName }).invoke('name').should('eq', 'Jane Lane');
cy.invoke(); // invokes a function (JS, jquery...) on the element

cy.get('.input').invoke('val').should('eq', 'foo'); // Invoke the 'val' function
cy.get('.modal').invoke('show'); // Invoke the jQuery 'show' function
cy.get('a.external').invoke('removeAttr', 'href'); // removes href attribute from "a.external" elements
cy.get('input').invoke('attr', 'id', 'new-id'); // changes "id" input attribute
cy.wrap({ animate: fn }).invoke('animate'); // Invoke the 'animate' function

Global variables

They can be defined in /cypress.env.json. To access it from the servers use:

Cypress.env("FIRST_JSON_LEVEL").SUBVARIABLE1.SUBVARIABLE2.SUBVARIABLEN

Plugins

get them on https://www.npmjs.com install it with:

npm install -D plugin-name

in the plugin information, it should say how to load it. It usually is adding on cypress/support/index.js:

require('plugin-name');

Example with https://www.npmjs.com/package/cypress-plugin-tab

npm install -D
require('cypress-plugin-tab');
cy.get('#inputFirstname').type('myName').tab().type('lastName');

Util plugins:

  • file-upload

Files structure

  • /bin: contains scripts to launch different type of tests
  • /cypress/e2e/.cy.js: contains the actual tests
  • fixtures: TBD
  • /support/custom_commands/: custom folder where project commands will be placed
  • /support/commands.js: commands and how cypress functions are named
  • /support/e2e.js: framework configuration file. Here we will import all custom commands files.
  • /cypress.config.js: default configurations for tests
  • /cypress.env.json: global variables