Skip to main content

Cypress Functions and Commands Explained

Cypress provides various functions and commands for writing automated tests effectively. Below is a categorized list of the most commonly used Cypress functions with explanations and examples.


1. Visiting and Navigating Pages

cy.visit(url)

    Navigates to a specific URL.


    cy.visit('https://example.com');
  • Can also pass options like authentication headers.

    cy.visit('https://example.com', { auth: { username: 'user', password: 'pass' } });

cy.go()

    Navigates forward or backward in browser history.

    cy.go('back'); // Go back one page     cy.go('forward'); // Go forward one page     cy.go(-1); // Equivalent to back     cy.go(1); // Equivalent to forward

cy.reload()

    Reloads the current page.

    cy.reload();     cy.reload({ force: true }); // Forces reload, bypassing cache

2. Selecting Elements

cy.get(selector)

Selects elements using a CSS selector.


    cy.get('#username'); // Selects an element with ID 'username'     cy.get('.btn-primary'); // Selects an element with class 'btn-primary'     cy.get('[data-testid="submit-button"]'); // Uses a test-specific attribute

cy.contains(text)

Finds elements containing specific text.


    cy.contains('Submit').click(); // Clicks a button containing 'Submit'     cy.contains('Welcome, John').should('be.visible');

cy.find(selector)

Finds a child element inside a parent.


    cy.get('.form-container').find('input').type('test');

cy.within()

Runs commands inside a specific DOM element.


cy.get('.login-form').within(() => { cy.get('input[name="username"]').type('student'); cy.get('input[name="password"]').type('Password123'); });

3. Interacting with Elements

cy.type(text)

Types text into an input field.


    cy.get('input[name="email"]').type('test@example.com');     cy.get('input[name="password"]').type('MyPassword{enter}'); // Simulates pressing Enter key

cy.clear()

Clears the input field.

    cy.get('input[name="username"]').clear();

cy.click()

Clicks on an element.

    cy.get('#login-button').click();     cy.get('#checkbox').click({ force: true }); // Clicks even if hidden

cy.check() / cy.uncheck()

Checks and unchecks checkboxes or radio buttons.


    cy.get('#accept-terms').check();         cy.get('#accept-terms').uncheck();

cy.select()

Selects a dropdown option.


    cy.get('select[name="country"]').select('USA');

4. Assertions (Validations)

cy.should()

Asserts conditions on elements.


    cy.get('.success-message').should('be.visible'); // Check visibility     cy.get('input').should('have.value', 'test@example.com'); // Check input value     cy.get('button').should('be.enabled'); // Check if button is enabled     cy.get('.error-message').should('contain', 'Invalid login'); // Check text content

cy.expect()

General assertion function.


    expect(true).to.be.true;     expect(5).to.equal(5);

cy.should('not.exist')

Checks if an element does NOT exist.


    cy.get('.modal').should('not.exist');

5. Handling Network Requests

cy.intercept(method, url)

Intercepts API calls and mocks responses.


    cy.intercept('GET', '/api/user', { fixture: 'user.json' }).as('getUser');     cy.wait('@getUser').its('response.statusCode').should('eq', 200);

cy.wait(alias)

Waits for an intercepted API request to finish.


    cy.wait('@getUser');

6. Handling Cookies and Local Storage

cy.setCookie(name, value)

Sets a browser cookie.

    cy.setCookie('session_id', '123456');

cy.getCookie(name)

Gets a cookie value.


    cy.getCookie('session_id').should('have.property', 'value', '123456');

cy.clearCookies()

Clears all cookies.


    cy.clearCookies();

cy.setLocalStorage(key, value)

Sets a value in local storage.


    cy.window().then((win) => {     win.localStorage.setItem('theme', 'dark');     });

cy.getLocalStorage(key)

Gets a value from local storage.


    cy.window().then((win) => {     expect(win.localStorage.getItem('theme')).to.equal('dark');     });

7. Debugging & Logs

cy.pause()

Pauses test execution at a specific point.


    cy.get('#submit').click().pause();

cy.debug()

Prints debugging information.


    cy.get('input').debug();

cy.log(message)

Logs custom messages to the Cypress command log.


    cy.log('User is logged in successfully');

8. Running Tests in CI/CD

cy.screenshot()

Takes a screenshot of the current state.

    cy.screenshot('login-success');

cy.task()

Runs Node.js functions within Cypress.

    cy.task('log', 'This is a debug message');

9. Running Cypress Tests

Run Cypress in interactive mode:

npx cypress open


Run tests headlessly:

npx cypress run


Run specific test file:

npx cypress run --spec cypress/e2e/login.cy.js

Conclusion

Cypress provides a comprehensive API for testing web applications efficiently. By using its built-in commands for navigation, element selection, interactions, assertions, and debugging, you can write reliable automated tests.


Comments

Popular posts from this blog

8 Mistakes Every Beginner Programmer Makes (and How to Avoid Them)

  Starting with programming can be exciting but also challenging. Every beginner makes mistakes—it's part of the learning process! However, knowing common pitfalls can help you improve faster. Here are eight mistakes every beginner programmer makes and how to avoid them. 1. Not Understanding the Problem Before Coding ❌ Mistake: Jumping straight into coding without fully understanding the problem can lead to messy, inefficient, or incorrect solutions. ✅ Solution: Take a step back and analyze the problem . Break it into smaller parts and think about the logic before writing any code. Use flowcharts, pseudocode, or even pen and paper to sketch out your solution. 📌 Example: Instead of diving into loops, first clarify what needs to be repeated and under what conditions. 2. Ignoring Error Messages ❌ Mistake: Many beginners panic when they see an error message and either ignore it or randomly change things to make the error disappear. ✅ Solution: Read the error message carefully —it of...

Understanding SQL Query Execution Order

When writing SQL queries, understanding the execution order is crucial for writing efficient and optimized code. Many beginners assume that queries execute in the order they are written, but in reality, SQL follows a specific sequence of execution. SQL Execution Order SQL queries run in the following order: 1️⃣ FROM + JOIN 2️⃣ WHERE 3️⃣ GROUP BY 4️⃣ HAVING 5️⃣ SELECT (including window functions) 6️⃣ ORDER BY 7️⃣ LIMIT Let’s break down each step with examples. 1. FROM + JOIN (Data Retrieval) The SQL engine first retrieves data from the specified table(s) and applies any JOIN operations. 🔹 Example: SELECT employees.name, departments.department_name FROM employees JOIN departments ON employees.department_id = departments.id; Here, the JOIN happens before any filtering ( WHERE ) or grouping ( GROUP BY ). 2. WHERE (Filtering Data) Once data is retrieved, the WHERE clause filters rows before aggregation occurs. 🔹 Example: SELECT * FROM employees WHERE salary > 50000 ; Thi...

Exploring the Latest AI Tools: Revolutionizing Productivity and Creativity

Artificial Intelligence (AI) continues to revolutionize various industries by providing powerful tools that enhance creativity, productivity, and efficiency. Here’s a curated list of the latest AI tools across different domains in 2024: Design Tools AI-powered design tools help streamline the creative process, making it easier to create stunning visuals, graphics, and branding materials. Autodraw – AI-assisted sketching tool. Flair AI – Generates high-quality product mockups. Booth AI – AI-driven photoshoot generator. Content Creation These tools assist in generating and enhancing content, from text to multimedia, making content production more efficient. Writesonic – AI-powered writing assistant for blogs and ads. Beautiful AI – Smart presentation design tool. Stocking AI – Generates realistic stock images. Clipdrop – Enhances and removes background from images. Steve AI – Converts text into animated videos. Tome – AI storytelling and presentation software. Murf AI – AI voic...