Writing Your First Assertion
Learn Writing Your First Assertion step by step with clear examples and exercises.
Title: Writing Your First Assertion - A full guide Using JavaScript Examples
Why This Matters
Assertions are essential in test automation as they allow us to verify that our scripts produce the expected results. They help in debugging, ensuring code quality, and making our tests more reliable. In this lesson, we will learn how to write assertions using JavaScript, a popular language for test automation with tools like Selenium, Cypress, and Playwright.
Importance of Assertions
Assertions play a crucial role in test automation by helping us:
- Verify the correctness of our scripts
- Debug issues quickly and efficiently
- Ensure code quality and reliability
- Provide feedback on test failures for further analysis
Prerequisites
Before diving into writing assertions, you should have a basic understanding of:
- JavaScript programming language
- Test automation concepts (what it is, why we use it)
- One test automation framework (Selenium, Cypress, or Playwright)
- Familiarity with the chosen test automation library's assertion functions and methods
Understanding the Test Automation Framework
To write effective assertions, you should be comfortable with your chosen test automation framework's capabilities and how to interact with web elements, such as locators, actions, and properties.
Core Concept
An assertion is a function that checks if a condition is true or false. In JavaScript, we can write custom assertions or use built-in ones provided by our chosen test automation framework.
Here's an example of a simple assertion using the expect function from Jest (a popular JavaScript testing library):
test('Asserting equality', () => {
const actual = 1 + 1;
const expected = 2;
expect(actual).toEqual(expected);
});
In this example, we're asserting that the value of actual (the result of adding 1 and 1) is equal to the expected value of 2. If the assertion fails, Jest will provide an error message indicating the issue.
Types of Assertions
Test automation libraries offer various built-in assertions for different use cases:
- Equality checks (
toEqual,toBe, etc.) - Strict equality checks (
expect(actual).toBe(expected)) - Truthy/falsy checks (
expect(actual).toBeTruthy(),expect(actual).toBeFalsy()) - Array and object comparison (
expect(array).toEqual([1, 2, 3]),expect(object).toEqual({ key: 'value' })) - Regular expression matches (
expect(string).toMatch(/regex/)) - Custom assertions (functions you create to check specific conditions)
Worked Example
Let's write a test using Selenium WebDriver with JavaScript that checks if the title of a webpage is "Test Automation."
const {Builder, By, Key, until} = require('selenium-webdriver');
async function testTitle() {
let driver = await new Builder().forBrowser('chrome').build();
try {
await driver.get('https://www.example.com/test-automation');
const title = await driver.getTitle();
expect(title).toEqual('Test Automation');
} catch (error) {
console.error(`Error occurred: ${error}`);
} finally {
await driver.quit();
}
}
testTitle();
In this example, we're using the getTitle() method to get the title of the webpage and comparing it with our expected value using the expect function. If the title doesn't match, an error will be thrown, helping us identify the issue in our test script.
Common Mistakes
- Not waiting for the page to load: Make sure you wait for the necessary elements to appear before making assertions about them.
- Asserting on incorrect values: Ensure that your
expectfunction is comparing the correct variables or properties. - Ignoring error messages: Pay attention to error messages when an assertion fails and use them to debug your test script.
- Not handling asynchronous operations properly: Use promises, async/await, or other methods to handle asynchronous operations correctly in your tests.
- Not cleaning up resources: Don't forget to close browser windows or quit the WebDriver session when you're done with your tests to free up system resources.
- Using incorrect assertion functions: Choose the appropriate assertion function based on the data type and expected result.
- Not providing meaningful error messages: Provide clear and descriptive error messages in custom assertions to help debug issues more effectively.
- Overcomplicating assertions: Keep assertions simple, focused, and easy to understand for maintainability purposes.
Common Mistakes - Examples
- Incorrect assertion function usage:
test('Incorrect assertion', () => {
const actual = 2;
expect(actual).toMatch(/regex/); // incorrect usage of toMatch()
});
- Lack of meaningful error messages:
function customAssertion(actual, expected) {
if (actual !== expected) throw new Error('Custom assertion failed');
}
test('Custom assertion with no message', () => {
const actual = 1;
const expected = 2;
customAssertion(actual, expected); // error message is not helpful
});
- Improper handling of asynchronous operations:
test('Improper async handling', async () => {
const actual = await getData(); // async function that takes some time to return
expect(actual).toEqual([1, 2, 3]); // assertion fails before data is available
});
- Not waiting for the page to load:
test('Not waiting for page load', () => {
const driver = new Builder().forBrowser('chrome').build();
driver.get('https://www.example.com/test-automation');
expect(driver.getTitle()).toEqual('Test Automation'); // assertion fails before page loads
});
Practice Questions
- Write a test using Cypress that checks if the text "Welcome" appears on the page.
- Write a test using Playwright that verifies the value of an input field with the ID
usernameis "testuser". - Write a test using Jest that asserts the sum of two numbers is equal to 5.
- Write a test using Selenium WebDriver that checks if a button with the text "Submit" is enabled (i.e., clickable).
FAQ
- What happens when an assertion fails in JavaScript? When an assertion fails, it throws an error, which can be caught and handled appropriately. The test will fail if the error isn't caught or handled correctly.
- Can I write custom assertions in JavaScript? Yes, you can create custom assertions by writing your own functions that check specific conditions. These custom assertions can then be used in your tests like built-in ones.
- What is the difference between
toEqualandtoBein Jest?toEqualchecks if two objects are equal (including their properties), whiletoBechecks if two values are strictly equal (without checking their properties). UsetoEqualwhen you want to compare complex objects, and usetoBefor simple values like numbers or strings. - How do I handle asynchronous operations in my tests? You can use promises, async/await, or other methods to handle asynchronous operations correctly in your tests. Make sure to wait for the necessary elements to appear before making assertions about them.
- What are some best practices when writing assertions? Keep assertions simple, focused, and easy to understand. Provide clear and descriptive error messages in custom assertions. Wait for the page to load before making assertions, and handle asynchronous operations properly.