top of page
Writer's pictureSinduja Jayakumar

Unleashing the Power of Cypress Testing: Part 4







Introduction:

Welcome back to the next chapter of our Cypress exploration! In the previous blog (https://manage.wix.com/dashboard/93eea007-719d-4338-a355-03d333fb982c/blog/523b3978-cb67-48f4-9271-4c83582ada76/edit?tab=published&lang=en) there has been a dedicated exploration into the foundational elements of Cypress—Browser Commands, Dropdowns, Checkboxes, and Wait Strategies with Cypress. 


As we progress on this journey, our focus now shifts to a other aspect of testing - handling Alerts, Iframes, WebTable,Assertion, Screen Shots.


VII- Handling Alerts:

Handling alerts in Cypress involves interacting with and asserting the behavior of JavaScript alerts, confirms, and prompts that may appear during the execution of your application. Here are examples of how you can handle alerts in Cypress:


1. Handling JavaScript Alerts:

Assuming you have a scenario where clicking a button triggers a JavaScript alert:

<!-- HTML with a button that triggers an alert -->

<button id="triggerAlert" onclick="alert('Hello, Cypress!')">Trigger Alert</button>

You can handle this alert in Cypress using the window:alert event:

// Trigger an alert by clicking a button

cy.get('#triggerAlertButton').click();

// Handle the alert by accepting it

cy.on('window:alert', (text) => {

  expect(text).to.equal('This is an alert!');

});

  • Explanation:

  • The cy.get('#triggerAlertButton').click() command simulates clicking a button that triggers an alert.

  • The cy.on('window:alert', ...) command listens for the window:alert event, which is triggered when an alert appears.

  • The callback function receives the alert text, and you can make assertions or perform actions based on that text.

2. Handling Confirm Dialogs:

// Trigger a confirm dialog by clicking a button

cy.get('#triggerConfirmButton').click();

// Handle the confirm dialog by accepting it

cy.on('window:confirm', () => true);

// Alternatively, handle the confirm dialog by dismissing it

// cy.on('window:confirm', () => false);

  • Explanation:

  • The cy.get('#triggerConfirmButton').click() command triggers a confirm dialog.

  • The cy.on('window:confirm', ...) command intercepts the window:confirm event and resolves it by returning true to accept the confirm dialog or false to dismiss it.


3. Handling Prompt Dialogs:

// Trigger a prompt dialog by clicking a button

cy.get('#triggerPromptButton').click();

// Handle the prompt dialog by providing a response

cy.on('window:prompt', (text, value) => {

  expect(text).to.equal('Please enter something:');

  return 'Cypress is awesome!';

});

Explanation:

  • The cy.get('#triggerPromptButton').click() command triggers a prompt dialog.

  • The cy.on('window:prompt', ...) command intercepts the window:prompt event, allowing you to provide a response to the prompt. The callback function receives the prompt text and the default value (if any).

VIII- Handling Iframes:

Handling frames in Cypress involves switching between different iframes or frames within a web page. Here's the basic syntax for working with frames in Cypress:


1. Switching to a Frame:

// Switch to a frame by its index

cy.frameLoaded(index).then(() => {

  cy.iframe(index).find('#elementInFrame').click();

});


2. Switching to a Frame by Name or ID:

// Switch to a frame by its name or ID

cy.iframe('frameNameOrId').find('#elementInFrame').click();


3. Switching Back to the Default Content:

// Switch back to the default content (outside of any frame)

cy.switchTo('default').find('#elementOutsideFrame').click();


Real-world Example:

// Visit a page with frames

// Switch to the first frame by index

cy.frameLoaded(0).then(() => {

  // Perform actions inside the first frame

  cy.iframe(0).find('#elementInFrame').click();

});

// Switch to the frame with name 'frameName'

cy.iframe('frameName').find('#elementInFrame').click();

// Switch back to the default content

cy.switchTo('default').find('#elementOutsideFrame').click();


IX- Handling WebTables:

Handling web tables in Cypress involves selecting table elements, navigating through rows and columns, and performing assertions or interactions with table data. Here's the basic syntax for working with web tables in Cypress:


1. Selecting Table Rows and Cells:

// Select a specific table row by index

cy.get('table tr').eq(1).click(); // Clicks on the second row

// Select a specific cell in a row

cy.get('table tr').eq(1).find('td').eq(2).should('contain', 'Data'); // Verifies the content of the third cell in the second row


Explanation:

  • cy.get('table tr').eq(1).click(): This command selects the second row (eq(1)) in the table and simulates a click action on it. You can modify the index to select a different row.

  • cy.get('table tr').eq(1).find('td').eq(2).should('contain', 'Data'): This command first selects the second row (eq(1)) and then finds the third cell (eq(2)) within that row. It asserts that the cell contains the text 'Data'. Adjust the indices as needed for your specific table structure.

2. Iterating Through Table Rows:

// Iterate through all rows in the table

cy.get('table tr').each((row, rowIndex) => {

  // Perform actions for each row

  cy.wrap(row).find('td').eq(0).should('contain', `Row ${rowIndex + 1}`);

});

  • Explanation:

  • cy.get('table tr').each((row, rowIndex) => { ... }): This command iterates through each row in the table. The callback function is executed for each row.

  • cy.wrap(row).find('td').eq(0).should('contain', Row ${rowIndex + 1}): For each row, it wraps the row element, finds the first cell (eq(0)), and asserts that it contains text based on the row index. This is a common pattern for iterating through rows and performing actions.

3. Asserting Table Content:

// Assert that a specific value is present in the table

cy.get('table').should('contain', 'Expected Value');


X-Mouse Actions:

Cypress supports various mouse actions that you can use to simulate user interactions with your web application. Here are some common mouse actions and their basic syntax:


1. Clicking on an Element:

// Click on a button with ID 'myButton'

cy.get('#myButton').click();


2. Double-Clicking on an Element:

// Double-click on an element with class 'myElement'

cy.get('.myElement').dblclick();


3. Right-Clicking on an Element:

// Right-click on a div with class 'contextMenu'

cy.get('.contextMenu').rightclick();


4. Triggering Mouseover/Hover:

// Hover over an element with ID 'hoverElement'

cy.get('#hoverElement').trigger('mouseover');


5. Dragging and Dropping:

// Drag and drop from source to target element

cy.get('#sourceElement').trigger('mousedown').trigger('mousemove', { clientX: 600, clientY: 200 }).trigger('mouseup');

cy.get('#targetElement').trigger('drop');


XI- Assertions:

Assertions in Cypress are used to verify the expected behavior or state of elements, values, or conditions in your web application during testing. Cypress provides a variety of assertion commands that make it easy to express your expectations. Here are some common assertions and their basic syntax:


1. Checking Element Existence:

// Assert that an element with ID 'myElement' exists

cy.get('#myElement').should('exist');

// Assert that an element with class 'myClass' does not exist

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


2. Checking Text Content:

// Assert that a paragraph contains the text 'Hello, World!'

cy.get('p').should('contain', 'Hello, World!');

// Assert that an input field has a specific value

cy.get('#myInput').should('have.value', 'Default Value');


3. Checking Visibility:

// Assert that a button is visible

cy.get('button').should('be.visible');

// Assert that a modal is hidden

cy.get('#myModal').should('not.be.visible');


4. Checking Attribute Values:

// Assert that an anchor tag has an 'href' attribute with a specific value

cy.get('a').should('have.attr', 'href', 'https://example.com');

// Assert that a checkbox is checked

cy.get('#myCheckbox').should('be.checked');


5. Checking Element State:

// Assert that a button is disabled

cy.get('#myButton').should('be.disabled');

// Assert that a radio button is selected

cy.get('input[name="gender"]').should('be.checked');


6. Checking Number of Elements:

// Assert that there are exactly 3 list items in an unordered list

cy.get('ul').find('li').should('have.length', 3);


XII- Captureing Screen Shots:

Cypress provides built-in capabilities to capture screenshots and videos during test execution. These features are invaluable for debugging and analyzing test failures, as they allow developers and testers to visually inspect the state of the application at specific points in the test execution. Let's explore how screenshots and videos in Cypress can enhance the testing process:


1. Capturing Screenshots:

Cypress makes it easy to take screenshots at specific steps in your test. This is particularly helpful when you encounter a test failure or want to visually inspect the application's state.

// Take a screenshot

cy.screenshot('my-screenshot'); // Saves the screenshot as 'my-screenshot.png' in the default screenshots folder

  • Benefits:

  • Visual confirmation of the application's state at a specific point in the test.

  • Easy identification of UI discrepancies or unexpected changes.

2. Capturing Videos:

Cypress can record videos of the entire test run, providing a comprehensive view of the test execution.

// Enable video recording

// This will record the entire test run and save it as a video file

Cypress.Screenshot.defaults({

  screenshotOnRunFailure: true,

});

  • Benefits:

  • Review the entire test run to identify patterns or issues that may not be evident in individual screenshots.

  • Share video recordings for collaborative debugging or reviewing test executions.

3. Screenshots on Test Failure:

Cypress can automatically capture screenshots when a test fails, making it easier to pinpoint issues.

// Automatic screenshot on test failure

it('should navigate to the home page', () => {

  cy.visit('/home');

  cy.get('#missingElement').click(); // This will cause a test failure

});

  • Benefits:

  • Immediate insight into the state of the application when a failure occurs.

  • Facilitates faster debugging by providing visual context for the failed test.

4. Screenshots and Command Log:

Cypress integrates screenshots with its command log, allowing you to view and download screenshots directly from the Cypress Test Runner.

  • Benefits:

  • Seamlessly navigate between commands and corresponding screenshots.

  • Simplifies the process of inspecting the application state at different test steps.

While we've covered a lot of important aspects of Cypress, there are a few additional topics to be consider are:

-Network Requests and API Testing

-Cypress Plugins

-Test Data Management

-Continuous Integration (CI) Integration



As we conclude our journey through Cypress, it's evident that this testing tool transcends the ordinary. From mouse actions to web tables, from screenshots to video recordings, Cypress equips developers with a comprehensive arsenal to ensure application stability and user satisfaction. The framework's ability to capture the essence of the user journey through visual elements enhances the debugging process, making it more intuitive and effective.

So, equip yourself with Cypress, explore its possibilities, and elevate your testing practices to new heights. The journey to testing excellence begins here.

Happy testing!



27 views

Recent Posts

See All
bottom of page