“Cypress Testing – Assertions Techniques Best Practices and Tips” focuses on enhancing the efficiency and effectiveness of test assertions in Cypress, a popular JavaScript end-to-end testing framework.
Cypress testing plays a crucial role in ensuring the reliability and correctness of web application tests. Developers and testers use these to validate expected outcomes, allowing them to assert conditions about the application’s state during test execution. Automation Testing.
We can summarise the key features of Assertions in Cypress Testing as:
- Rich Assertions: Comprehensive checks for element properties (existence, visibility, text content, attributes).
- Seamless Integration: Assertions smoothly blend into test syntax, improving readability and maintenance.
- Automatic Retry: Robust handling of asynchronous tasks, minimizing test flakiness.
- Expressive Tests: Empowers developers to create clear, comprehensive, and efficient tests, boosting confidence in the testing process.
Assertions in Cypress Testing:
Verify that an element exists in the DOM:
Syntax: .should(‘exist’)
Example:
<body>
<button id="myButton">Click me</button>
</body>
cy.get('button#myButton').should('exist');
Verify that an element does not exist in the DOM:
Syntax: .should(‘ not.exist ‘)
Example:
<body>
<button id="myButton">Click me</button>
</body>
cy.get('button#myButton').should(‘not.exist’)
Verify that an element is visible/Not Visible:
Syntax: .should(‘be.visible ‘) .should(‘not.be.visible ‘)
Example:
<button id="myButton">Visible Button</button>
<button id="hiddenButton">Hidden Button</button>
//To check visibility of element
cy.get(' button#myButton ').should('be.visible')
//To check invisibility of element
cy.get('button#hiddenButton').should('not.be.visible');
Verify that an element is hidden:
Syntax: .should(‘be.hidden)
Example:
<body>
<div id="hiddenElement">This element is hidden</div>
</body>
cy.get('#hiddenElement').should('be.hidden');
Verify that an element has the expected value that the user has entered in the textbox:
Syntax: .should(‘have.value’, ‘expectedValue’)
Example:
<body>
<input type="text" id="myTextbox" />
</body>
cy.get('#myTextbox').type("Hello SpurQLabs”);
cy.get('#myTextbox').should('have.value', 'Hello SpurQLabs');
Verify that a string includes the expected substring:
Syntax: .should(‘include’, ‘expectedSubstring’)
Example:
<title>Cypress Example</title>
<body>
<div id="myText">This is some text content.</div>
</body>
// Verify that the text content includes the expected substring
const expectedSubstring = 'some text';
cy.get('#myText').should('include.text', expectedSubstring);
Verify that a string matches a regular expression pattern:
Syntax: .should(‘match’, /regexPattern/)
Example:
<title>Cypress Example</title>
<body>
<div id="myText">This is some text content.</div>
</body>
// Verify that the text content matches a regular expression pattern
const regexPattern = /some.*content/;
cy.get('#myText').invoke('text').should('match', regexPattern);
Verify the length of an array or the number of elements matched:
Syntax: .should(‘have.length’, expectedLength)
Example:
<title>Cypress Example</title>
<body>
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
const expectedLength = 3;
cy.get('#myList li').should('have.length', expectedLength);
Verify if the element is focused:
Syntax: .should(‘have.focus’)
.should(‘be.focused’)
Example:
<title>Cypress Example</title>
<body>
<input type="text" id="myInput" />
</body>
// Focus on the input element
cy.get('#myInput').focus();
// Verify that the input element is focused
cy.get('#myInput').should('have.focus');
cy.get('#myInput').should('be.focused ');
Verify the title of the page:
Syntax: .title().should(‘include’, ‘Example Domain’)
Example:
<title>Cypress Example</title>
const expectedTitle = 'Cypress Example';
cy.title().should('eq', expectedTitle);
cy.title().should('include', expectedTitle )
Verify the URL:
Syntax: .url().should(‘eq’, ‘https://www.spurqlabs.com’);
Example:
cy.visit('https://www.spurqlabs.com');
const expectedURL = 'https://www.spurqlabs.com';
cy.url().should('include', expectedURL);
Verify multiple assertions at a time:
Example:
cy.get('h1')
.should('exist') // Assertion 1: Check if the h1 element exists
.and('be.visible') // Assertion 2: Check if the h1 element is visible
.and('have.text', 'Example Domain'); // Assertion 3: Check if the h1 element has the expected text
Property Assertion in Cypress Testing
Verify that an element has the expected attribute value:
Syntax: .should(‘have.attr’, ‘attributeName’, ‘expectedValue’)
Example:
<title>Cypress Example</title>
<body>
<div id="myElement" data-custom-attribute="example-value">Some content</div>
</body>
const attributeName = 'data-custom-attribute';
const expectedValue = 'example-value';
cy.get('#myElement').should('have.attr', attributeName, expectedValue);
});
Verify that an element has a specific CSS property with the expected value:
Syntax: .should(‘have.css’, propertyName, Value)
Example:
<title>Cypress Example</title>
<style>
#myElement {
color: blue;
font-size: 16px;
}
</style>
<body>
<div id="myElement">Styled element</div>
</body>
const propertyName = 'color';
const expectedValue = 'blue';
cy.get('#myElement').should('have.css', propertyName, expectedValue);
Verify that an element has the expected text content:
Syntax: .should(‘have.text’, expectedText)
Example:
<title>Cypress Example</title>
<body>
<div id="myElement"> SpurQLabs </div>
</body>
const expectedText = 'SpurQLabs';
cy.get('#myElement').should('have.text', expectedText);
Verify that an input element has the expected value:
Syntax: .should(‘have.value’, expectedValue )
Example:
<title>Cypress Example</title>
<body>
<input type="text" id="myInput" value="SpurQLabs" />
</body>
const expectedValue = 'SpurQLabs';
cy.get('#myInput').should('have.value', expectedValue);
Verify that a given value is NaN, or “not a number”:
Syntax: .should(‘be.a.NaN’)
Example:
// Some operation that results in NaN, for example, dividing by zero
const result = 1 / 0;
// Verify that the result is NaN
1) cy.wrap(result).should('be.a.NaN');
2) cy.wrap(result).then(value => {
expect(value).to.not.be.NaN;
});
Verify an element or collection of elements is empty:
Syntax: .should(‘be.empty’)
.should(‘not.be.empty’)
Example:
<body>
<div id="emptyElement"></div>
<div id="nonEmptyElement">Some content</div>
</body>
// Verify that the empty element is empty
cy.get('#emptyElement').should('be.empty');
// Verify that the non-empty element is not empty
cy.get('#nonEmptyElement').should('not.be.empty');
Verify if a checkbox or radio button is checked:
Syntax: .should(‘be.checked’)
Example:
<body>
<input type="checkbox" id="myCheckbox" checked />
<input type="radio" id="myRadioButton" checked />
</body>
cy.get('#myCheckbox').should('be.checked');
cy.get('#myRadioButton').should('be.checked');
Verify if a checkbox or radio button is not checked:
Syntax: .should(‘not.be.checked’)
Example:
cy.get('#myCheckbox').should('not.be.checked');
cy.get('#myRadioButton').should('not.be.checked');
Verify if it is an array:
Syntax: .should(‘be.an’,’array’)
Example:
const myArray = [1, 2, 3];
cy.wrap(myArray).should(value => {
expect(value).to.be.an('array');
});
cy.get('myArray’).should(‘be.an’,’array’)
Verify if an object has specific keys:
Syntax: .should(‘have.keys’,[‘id’,’name’,’email’])
Example:
const myObject = {
key1: 'value1',
key2: 'value2',
key3: 'value3'
};
// Define the expected keys
const expectedKeys = ['key1', 'key2', 'key3'];
// Verify that the object has the expected keys
cy.wrap(myObject).should(obj => {
expect(Object.keys(obj)).to.deep.equal(expectedKeys);
});
cy.get('#object’).should('have.keys', ['id', 'name', 'email'])
Verify if a value is one of a specific set of values:
Syntax: .should(‘be.oneOf’,[‘value1′,’value2′,’value3’])
Example:
cy.get(''YourCSSelement ').should('be.oneOf', ['red', 'green', 'blue'])
Verify that a numeric value is within a certain range of another value:
Syntax: .should(‘be.closeTo’, expectedValue, delta))
.should(‘be.within’, Start range, End range);
Example:
const actualValue = 15;
const referenceValue = 10;
const range = 5;
// Verify that the actual value is within the specified range of the reference value
cy.wrap(actualValue).should('be.within', referenceValue - range, referenceValue + range);
});
// Verify that the actual value is close to the expected value within the specified delta
cy.wrap(actualValue).should('be.closeTo', 50, 2); // Verify that actual value is close to (50-2) to (50+2) i.e. 48 to 52.
Verify Object assertion:
Syntax: .should(‘have.property’, ‘propertyName’,’actualPropertyValue’)
Example:
const expectedObject = {
name: 'Tom Cruise’,
age: 32,
city: ‘London’
}
cy.wrap(expectedObject)
.should('have.property', 'name', expectedObject.name)
.should('have.property', 'age', expectedObject.age)
should('have.property', 'city', expectedObject.city)
Check is() block Assertions:
In the context of Cypress Testing, the .is() block typically utilizes conditions that check various states or attributes of an element. Here are some examples of selectors and conditions you might use inside the .is() block:
- Check if an element is visible:
if($element.is(':visible')){
// Code to execute when the element is visible
}
- Check if a button or input is enabled:
if ($element.is(':enabled')) {
// Code to execute when the element is enabled
}
- Check if an input field is readonly:
if ($element.is('[readonly]')) {
// Code to execute when the element is readonly
}
- Check if an element contains specific text:
if ($element.is(':contains("Some Text")')) {
// Code to execute when the element contains the specified text
}
- Check if an element has a specific attribute value:
if ($element.is('[data-type="value"]')) {
// Code to execute when the element has the specified attribute value
}
- Create custom conditions based on your specific requirements:
if ($element.is('.custom-class')) {
// Code to execute when the element has a specific class
}
Conclusion:
Cypress Testing with its rich set of functionalities and integration benefits, empowers developers to create expressive and comprehensive tests. The combination of these features fosters a more efficient and confident testing process, ultimately contributing to the overall reliability of web applications.
4Harish is an SDET with expertise in API, web, and mobile testing. He has worked on multiple Web and mobile automation tools including Cypress with JavaScript, Appium, and Selenium with Python and Java. He is very keen to learn new Technologies and Tools for test automation. His latest stint was in TestProject.io. He loves to read books when he has spare time.