Language: JavaScript
Testing
Cypress was created to improve the developer experience for testing web applications. Unlike traditional Selenium-based tools, Cypress runs in the same run-loop as the application, providing faster execution, automatic waiting, and real-time reloads. It is particularly popular for testing React, Vue, Angular, and other modern frontend frameworks.
Cypress is a next-generation front-end testing tool built for the modern web. It allows developers to write end-to-end, integration, and unit tests for web applications with fast, reliable, and easy-to-debug tests.
npm install cypress --save-devyarn add cypress --devCypress allows you to write tests in JavaScript using a simple, readable syntax. It provides automatic waiting for commands, real-time reloads, time-travel debugging, and screenshots or video recording of test runs.
describe('My First Test', () => {
it('Visits the Kitchen Sink', () => {
cy.visit('https://example.cypress.io')
cy.contains('type').click()
cy.url().should('include', '/commands/actions')
})
})Opens a webpage, clicks on a link containing the text 'type', and asserts that the URL includes '/commands/actions'.
describe('Input Test', () => {
it('Types into an input', () => {
cy.visit('https://example.cypress.io/commands/actions')
cy.get('.action-email').type('hello@example.com').should('have.value', 'hello@example.com')
})
})Finds an input element, types a value, and asserts that the input contains the expected value.
cy.intercept('GET', '/users', { fixture: 'users.json' }).as('getUsers')
cy.visit('/users')
cy.wait('@getUsers')Mocks a GET request to '/users' with a fixture and waits for the request to complete.
Cypress.Commands.add('login', (email, password) => {
cy.get('#email').type(email)
cy.get('#password').type(password)
cy.get('button[type=submit]').click()
})
// usage in a test
cy.login('user@example.com', 'password123')Defines a reusable custom command for logging in.
cy.get('input[type=file]').attachFile('example.json')Uses the Cypress file upload plugin to attach a file to an input element.
cy.get('.todo-list li').should('have.length', 3).and('contain', 'Buy milk')Performs multiple assertions on selected elements using Cypress + Chai syntax.
Use `.as()` and `cy.wait()` to manage network requests reliably.
Leverage custom commands for reusable actions to simplify tests.
Keep tests isolated and independent for consistent results.
Use fixtures for consistent test data.
Run Cypress in CI environments using headless mode for automated pipelines.