List of Assertions (Test Automation)
Learn List of Assertions (Test Automation) step by step with clear examples and exercises.
Title: List of Assertions (Test Automation) Using JavaScript Examples
Why This Matters
In test automation, assertions play an essential role in verifying that an application behaves as expected. They help in identifying and reporting failures in the system under test. By understanding various types of assertions available in test automation frameworks like Selenium, Cypress, and Playwright, you can write robust and reliable tests for your web applications.
The Importance of Assertions
Assertions are crucial for ensuring that the expected behavior of an application is met during testing. They help in identifying discrepancies between the actual and expected outcomes, making it easier to pinpoint issues and improve the quality of the application.
Prerequisites
To follow this lesson, you should have a basic understanding of:
- JavaScript programming language
- HTML and CSS basics
- One test automation framework (Selenium, Cypress, or Playwright)
- Familiarity with web development concepts such as DOM manipulation, AJAX requests, cookies, and event handling
- Understanding of asynchronous JavaScript programming using Promises or async/await
Core Concept
Assertions are statements that check the expected outcome of a test against the actual result. They help in validating the application's behavior during testing. In JavaScript-based test automation frameworks like Selenium, Cypress, and Playwright, you can use various assertion methods to compare the expected and actual values.
Types of Assertions
- Equality Assertions: These assertions are used to verify if two values are equal or not. Examples include
assert.equal(),expect(value1).toEqual(value2).
expect(actualValue).toEqual(expectedValue); // Cypress example
assert.strictEqual(actualValue, expectedValue); // Jest (for Node.js) example
- Numerical Assertions: These assertions are used for numerical comparisons, such as checking if a value is greater than, less than, or approximately equal to another value. Examples include
assert.strictEqual(),expect(value1).toBeGreaterThan(value2).
expect(actualValue).toBeGreaterThan(expectedValue); // Cypress example
assert.notStrictEqual(actualValue, expectedValue); // if actualValue should be greater than expectedValue
- String Assertions: These assertions are used for string comparisons, such as checking if two strings are identical, contain a specific substring, or match a regular expression. Examples include
assert.strictEqual(),expect(value1).toContain(substring).
expect(actualValue).toContain(expectedSubstring); // Cypress example
assert.strictEqual(actualValue, expectedValue.replace(/[^a-zA-Z0-9]/g, "")); // remove non-alphanumeric characters before comparison
- Object Assertions: These assertions are used to verify the properties and structure of objects. Examples include
expect(object).toHaveProperty(propertyName),expect(array).toEqual([expectedArray]).
expect(actualObject).toHaveProperty('propertyName'); // Cypress example
expect(actualArray).toEqual(expectedArray); // Jest (for Node.js) example
- Array Assertions: These assertions are used for array comparisons, such as checking if two arrays have the same elements or not. Examples include
expect(array1).toEqual(array2).
expect(actualArray).toEqual(expectedArray); // Cypress example
- Function Assertions: These assertions are used to verify the behavior of functions, such as checking if a function throws an error or returns a specific value. Examples include
assert.throws(),expect(functionCall()).toThrowError('expected error message').
expect(actualFunction).toThrowError('expected error message'); // Jest (for Node.js) example
Worked Example
Let's consider a simple example using Selenium WebDriver with JavaScript:
const {Builder, By, Key, until} = require('selenium-webdriver');
async function testExample() {
let driver = await new Builder().forBrowser('chrome').build();
try {
await driver.get('http://www.example.com');
let title = await driver.findElement(By.tagName('title')).getText();
expect(title).toEqual('Example Domain');
// Check if the page contains a specific element
await driver.wait(until.elementLocated(By.id('example-element')), 10000);
let element = await driver.findElement(By.id('example-element'));
expect(element).toBeVisible();
// Close the browser
await driver.quit();
} catch (error) {
console.log(`Error: ${error}`);
}
}
In this example, we first initialize a WebDriver instance for Chrome and navigate to the example domain. Then, we use findElement() to locate the page title and compare it with the expected value using toEqual(). We also verify if an element with the id "example-element" is visible on the page by waiting for its presence and checking its visibility status using toBeVisible().
Common Mistakes
- Not using assertions: Failing to use assertions in your tests can lead to unverified assumptions, making it difficult to identify if the test has passed or failed.
- Using incorrect assertion methods: Using the wrong assertion method for a given comparison can result in unexpected test results and hard-to-debug issues.
- Forgetting to handle exceptions: Not handling exceptions properly can cause tests to fail silently, making it difficult to identify the root cause of the failure.
- Ignoring timeouts: Ignoring timeouts during element locating or waiting for page elements can lead to test failures due to timeouts expiring before the expected condition is met.
- Not using explicit waits: Using implicit waits can result in tests failing due to elements not being ready when the test executes. Explicit waits ensure that you only wait for the specific element or condition you are interested in.
- Not handling asynchronous operations properly: Failing to handle asynchronous operations correctly can lead to unexpected results and hard-to-debug issues. Use Promises or async/await to manage asynchronous tasks effectively.
Practice Questions
- Write a Selenium WebDriver test using JavaScript to verify if the title of
http://www.example.comis "Example Domain". - Write a Cypress test to check if an element with the id "example-element" exists on the page and its text content is "Example Text".
- Write a Playwright test using JavaScript to verify that the value of an input field with the id "example-input" is "Example Value".
- Write a Cypress test to check if the webpage contains an element with the class "example-class" and has more than 5 child elements.
- Write a Selenium WebDriver test using JavaScript to verify that the value of a specific dropdown menu option with the text "Option A" is selected.
FAQ
- What happens if an assertion fails during a test run?
- If an assertion fails, it will throw an error, and the test will be marked as failed. The entire test suite will continue to run unless you have configured it to stop at the first failure.
- Can I use multiple assertions in a single test case?
- Yes, you can use multiple assertions within a single test case to validate different conditions or properties of your application.
- What is the difference between
assert.equal()andexpect(value1).toEqual(value2)?
- Both methods are used for equality checks, but
assert.equal()does not perform a deep comparison (i.e., it only checks if the values are strictly equal), whileexpect(value1).toEqual(value2)performs a deep comparison using JavaScript's built-inObject.is()function.
- How can I handle exceptions in my tests?
- You can use try-catch blocks to handle exceptions within your test cases. In the catch block, you can log the error or take appropriate action based on the exception type.
- What is the recommended approach for handling timeouts during element locating or waiting for page elements?
- It's best practice to use explicit waits instead of implicit waits. Explicit waits allow you to specify a maximum wait time and only wait for the specific condition you are interested in, reducing the risk of timeouts.
- What is the difference between implicit waits and explicit waits?
- Implicit waits add a global wait time before each action (e.g.,
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS)in Selenium WebDriver), while explicit waits allow you to specify a maximum wait time for a specific condition (e.g.,WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, 'example-element')))in Selenium WebDriver). Explicit waits are more flexible and recommended over implicit waits.
- How can I handle asynchronous operations in my tests?
- You can use Promises or async/await to manage asynchronous tasks effectively. For example, in Cypress:
cy.get('#example-element').then((element) => {
// Asynchronous operation here
expect(element).to.have.text('Example Text');
});