“Cypress” is a one of the best front end test automation tool for modern web applications. In this video, we have prepared some most asked cypress tool interview questions and answers for freshers & experienced 2023.
Cypress is an open source and free test automation tool for front end web applications. It was written in JavaScript based on Nodejs. It allows developers to write end-to-end tests that simulate user interactions with their web application and provide confidence that the application is working as expected.
Some of the key features of Cypress include:
Cypress and Selenium are both automated testing frameworks for web applications, but there are some key differences between them: Languages: Cypress Supports only JavaScript/Typescript languages (Based on Nodejs.) while Selenium supports all major languages like C#, Java, Python, JavaScript, Ruby, etc. Speed: Cypress is designed for speed and can run tests much faster than Selenium. This is because Cypress is built to run directly in the browser, whereas Selenium relies on the WebDriver API and can suffer from performance issues. Architecture: Cypress and Selenium have different architectures. Cypress runs directly in the browser, while Selenium interacts with the browser using the WebDriver API. This means that Cypress has more control over the browser environment and can offer faster test execution. Debugging: Cypress provides a built-in test runner and debugger, making it easy to debug tests in real time. Selenium, on the other hand, requires the use of external tools for debugging. Cross-browser support: Selenium has better cross-browser support compared to Cypress. Selenium supports a wide range of browsers, while Cypress currently only supports Chrome, Firefox, and Edge. APIs: Cypress has a more extensive and user-friendly API compared to Selenium. Cypress provides a simplified and intuitive API for interacting with elements on the page, while Selenium requires more complex code to perform the same tasks.
To create a test suite in Cypress, you can follow these steps: Create a new file: Open your project in your favorite code editor and create a new file in the cypress/integration folder Write your test cases: Write your individual test cases within the test suite file using Cypress commands. Each test case should be contained within a describe block, which provides a label for the test suite and groups related test cases together  For example: describe (‘Test Suite’, () => {  it(‘Tc01, () => {    // Your test case code  });  it(‘Displays an error message with invalid credentials’, () => {    // Your test case code  }); }); Run your test suite: Once you have written your test cases, you can run your test suite using the Cypress test runner. To do this, open a terminal window and run the following command: npx cypress run –spec cypress/integration/my-test-suite.js This will run all the test cases in the my-test-suite.js file.
Here are the main components of Cypress: Cypress Test Runner: It is a GUI that allows you to run and manage your tests. It provides a real-time view of your application as you interact with it, and allows you to debug and modify your tests on the fly. Cypress Dashboard: It is a web-based service that provides insights and analytics on your test runs. It allows you to view test results, compare test runs, and monitor the performance of your application over time. Cypress Command Line Interface (CLI): It is a command-line interface that allows you to run your tests in a headless environment, such as a CI/CD pipeline or a remote server. Cypress API: It provides a rich set of commands and utilities for interacting with your application and asserting its behaviour. It includes commands for navigating to pages, interacting with elements, making network requests, and more.
Here are some of the most commonly used Cypress commands: cy.visit(url): Visits a web page at the specified URL. cy.get(selector): Selects an element on the page using a CSS selector. cy.clear(): Clears the value of the selected input element. cy.wait(time): Pauses the test execution for the specified amount of time. cy.contains(text): Selects an element that contains the specified text. cy.click(): Triggers a click event on the selected element. cy.type(text): Types the specified text into the selected input element. cy.expect(actual).to.equal(expected): Asserts that the actual value is equal to the expected value. cy.getCookie(name): Retrieves the value of a cookie with the specified name. cy.intercept(url, handler): Intercepts network requests to the specified URL and allows you to modify the request or response.
Mocha and Chai are both popular JavaScript testing libraries, with Mocha providing a test runner and Chai providing an assertion library. Mocha is often used in conjunction with Chai for writing tests and making assertions. Chai provides a variety of assertion styles including expect, assert, and should.
Yes, Cypress does support XPath selectors. To use an XPath selector in Cypress, you can use the cy.xpath() command, which allows you to locate elements using an XPath expression. Here’s an example of how to use cy.xpath(): cy.xpath(‘//button[contains(text(), “Submit”)]’) Â .click();
By using the should assertion. cy.title().should(‘eq’,’My Site Title’)
Cypress provides several types of assertions that you can use to verify the behaviour of your web application. Here are some of the most commonly used assertion types in Cypress: Value assertions: To verify that a particular value matches an expected value. For example, you can use cy.get().should(‘have.value’, ‘expected value’) to assert that the value of an input field matches an expected value. Visibility assertions:Â To verify that an element is visible or not visible on the page. For example, you can use cy.get().should(‘be.visible’) to assert that an element is visible on the page. Existence assertions: To verify that an element exists or doesn’t exist on the page. For example, you can use cy.get().should(‘exist’) to assert that an element exists on the page. State assertions: To verify that an element has a particular state or attribute value. For example, you can use cy.get().should(‘have.class’, ‘class-name’) to assert that an element has a particular CSS class. Chaining assertions: To chain multiple assertions together to create more complex assertions. For example, you can use cy.get().should(‘be.visible’).and(‘have.class’, ‘class-name’) to assert that an element is visible and has a particular CSS class. These are just some of the most commonly used assertion types in Cypress. Cypress also provides additional assertion types, such as length, text, url, and title, among others.
Early Cypress provides a cy.route() command that you can use to manage the behaviour of network requests in your tests. It allows you to intercept and modify network requests made by your application, and to stub or mock responses to those requests. Here’s an example of how to use cy.route() to stub a response to a network request: cy.route(‘GET’, ‘/api/users’, [{ id: 1, name: ‘John’ }]); cy.visit(‘/users’); cy.get(‘.user’).should(‘have.length’, 1);
cy.intercept() command in Cypress allows you to intercept and modify HTTP requests and responses made by your application.
You need to pause your test for a certain amount of time, you can use the cy.wait() command with a specified duration. Here’s an example of how to use cy.wait() to pause your test for 3 seconds: cy.wait(3000);
To access the shadow DOM in Cypress, you can use the .shadow() method to retrieve the shadow root element of a custom element. Here’s an example of how to access the shadow DOM of a custom element with the tag name my-element: cy.get(‘my-element’).shadow()
By using the Cypress.Commands.add() method. Custom commands can be used to encapsulate commonly used test steps, reduce duplication in your test code, and make your tests more readable and maintainable. Here’s an example of how to create a custom command to log in to your application: Create a new file in your cypress/support/ directory called commands.js. In this file, define your custom command using the Cypress.Commands.add() method. Here’s an example: csharp Cypress.Commands.add(‘login’, (username, password) => { Â cy.visit(‘/login’); Â cy.get(‘#username’).type(username); Â cy.get(‘#password’).type(password); Â cy.get(‘#login-button’).click(); }); Save the commands.js file. In your cypress/support/index.js file, import your commands.js file. Here’s an example: import ‘./commands’; You can now use your custom command in your test code like this: cy.login(‘myusername’, ‘mypassword’);
we can change baseUrl dynamically by passing baseUrl in command line. This is how baseurl is defined in cypress.json file { Â “baseUrl”: Cypress.env(‘CYPRESS_BASE_URL’) } You can now run your tests with the new baseUrl by running the following command: cypress run –env CYPRESS_BASE_URL=http://localhost:3001You can override the same using command line In this example, we’re setting the CYPRESS_BASE_URL environment variable to http://localhost:3001 at runtime using the –env option.
In Cypress, you can use the cypress-failed-log plugin to re-run failed tests. Here are the steps to follow: Install the cypress-failed-log plugin by running the following command in your terminal: npm install cypress-failed-log –save-dev Import the plugin in your cypress/support/index.js file: require(‘cypress-failed-log’); Run your tests with the –env ci=true option to enable the plugin: npx cypress run –env ci=true After the test run completes, the plugin will create a new spec file called cypress/integration/failed/failed.js that contains the failed tests. To re-run the failed tests, run the following command: npx cypress run –spec “cypress/integration/failed/failed.js” This will run only the failed tests and generate a new set of results. You can repeat steps 4 and 5 as many times as needed until all the tests pass. Note that the cypress-failed-log plugin only works with the Cypress test runner, and not with the Cypress Test Runner GUI.
You can simulate key presses and typing in Cypress using the cy.type() command.
Cypress does not support testing multiple tabs or windows within a single browser instance. This is because Cypress is designed to simulate user interactions within a single browser tab, and does not have direct access to other tabs or windows. However, there are some workarounds that can be used to test multi-tab scenarios in Cypress:
Cypress has a default command timeout of 4 seconds, which means that if a command takes longer than 4 seconds to complete, Cypress will automatically fail the test. However, you can change the command timeout by setting the defaultCommandTimeout configuration option in your cypress.json or cypress.env.json file. For example, to set the timeout to 10 seconds: { Â “defaultCommandTimeout”: 10000 }
The “preserveOnce” option in Cypress allows you to preserve cookies across multiple test runs. By default, Cypress clears all cookies between test runs to ensure a clean slate for each test. However, there may be cases where you want to preserve certain cookies across multiple tests, for example to maintain user sessions or simulate a returning user. To preserve a cookie, you can use the cy.setCookie() command with the preserveOnce option set to true. For example: cy.setCookie(‘myCookie’, ‘myValue’, { preserveOnce: true });
You can view the default configuration of Cypress by running the following command in your terminal: npx cypress run –config
To perform API testing in Cypress, you can use the built-in cy.request() command to make HTTP requests to your API endpoints and then use Cypress assertions to verify the response. Here’s an example of how to make an API request and verify the response status code and body: cy.request(‘GET’, ‘https://api.example.com/posts/1’) Â .then((response) => { Â Â Â expect(response.status).to.eq(200) Â Â Â expect(response.body.title).to.eq(‘First Post’) Â }) This code will make a GET request to https://api.example.com/posts/1, and then use Cypress assertions to verify that the response has a status code of 200 and that the title property in the response body is equal to ‘First Post’. You can also use the cy.route() command to intercept and stub API requests for more complex scenarios, such as testing error handling or testing with specific request and response payloads. Here’s an example of how to use cy.route() to stub a POST request and verify the response: cy.server() cy.route({ Â method: ‘POST’, Â url: ‘https://api.example.com/posts’, Â status: 201, Â response: { Â Â Â id: 1, Â Â Â title: ‘New Post’ Â } }) cy.visit(‘/create-post’) cy.get(‘form’).submit() cy.get(‘.success-message’) Â .should(‘be.visible’) Â .and(‘contain’, ‘Post created successfully’) This code sets up a route that intercepts POST requests to https://api.example.com/posts, and stubs the response with a status of 201 and a body containing an id and title property. Then, it visits a page with a form to create a new post, submits the form, and verifies that a success message is displayed on the page.
While Cypress is a powerful and popular end-to-end testing framework, there are some potential downsides and limitations to consider: Large test files: Because Cypress tests are written in JavaScript and include both the test logic and the application code, test files can become large and complex. This can make them more difficult to maintain and debug. Limited browser support: Cypress currently only supports Chrome, Chromium, Edge, and Firefox browsers. This can be a limitation if you need to test on other browsers or older versions of supported browsers. Network requests interception: While Cypress’s ability to intercept network requests is a powerful feature, it can also lead to increased test complexity and potential synchronization issues. UI-only testing: Cypress is primarily focused on UI testing and does not offer built-in support for testing non-UI components such as APIs or databases. While it is possible to test these components with additional plugins and libraries, it can add complexity to your testing setup. Slow test execution: Cypress tests can be slower to execute than other testing frameworks due to its synchronous command queue and use of browser automation. This can be mitigated through efficient test design and execution strategies
What do you know about Cypress?
What are the different features of Cypress?
How Cypress is different than Selenium?
How to create a test suit in Cypress?
What are the main components of Cypress?
What are the most commonly used Cypress commands?
What is the difference between Mocha and Chai libraries?
Can we use XPath in Cypress?
How to verify the title of the page in Cypress?
How many types of assertions are available in Cypress?
Which command is used in Cypress to manage the behaviour of network requests?
What is the use of cy.intercept() command?
How to use wait () in Cypress?
How to access shadow DOM in Cypress?
How to create our custom commands in Cypress?
How can I change the baseUrl in Cypress dynamically?
How to re-run the failed test cases?
How can I type Keypress in Cypress?
How to use multitabs in Cypress?
How to set command timeout in cypress?
What is Preserve cookies in Cypress?
How can see the default configuration in Cypress?
How to perform API testing in Cypress?
What are the cons of using Cypress?