Select Page

Category Selected: Automation Testing

161 results Found


People also read

Accessibility Testing

Cypress Accessibility Testing: Tips for Success

Automation Testing

Test Automation Maintenance Costs: Smart Ways to Reduce

Accessibility Testing

Accessibility Testing with Playwright: Expert Guide

Talk to our Experts

Amazing clients who
trust us


poloatto
ABB
polaris
ooredo
stryker
mobility
Essential Guide to Allure Report WebdriverIO

Essential Guide to Allure Report WebdriverIO

In test automation, having clear and detailed reports is really important. A lot of teams that work with WebdriverIO pick Allure Report as their main tool. The Allure reporter connects your test results with helpful insights. This helps you understand the results of your test automation better. This blog will explain how to use Allure reporting in your WebdriverIO projects.

Key Highlights

  • This blog tells you about Allure Report. It shows how it works with WebdriverIO to help make test reports better.
  • You will learn how to set up Allure and make it run smoothly. It will also explain how to customize it.
  • You can see the benefits of using Allure, such as detailed test reports, useful visuals, and improved teamwork.
  • You will find handy tips to use Allure’s special reporting features to speed up your testing.
  • This guide is meant for both new and experienced testers who want to enhance their reporting with WebdriverIO.

Understanding the Need for Enhanced Reporting in WebdriverIO

Imagine this: you created a group of automated tests with WebdriverIO and Selenium. Your tests run well, but the feedback you receive is not enough to understand how good your automation is. Regular test reports usually do not have the detail or clarity needed to fix problems, review results, and talk about your work with others.
Allure is the place to get help. It is a strong and flexible tool for reporting. It takes your WebdriverIO test results and makes fun and useful reports. Unlike other simple reporting tools, Allure does more than just tell you which tests passed or failed. It shows you a clear picture of your test results. This allows you to see trends, find problems, and make good choices based on the data.

Identifying Common Reporting Challenges

One common issue in test automation is the confusing console output when tests fail. Console logs can help, but they are often messy and hard to read, especially when there are many tests. Another problem is how to share results with the team. Just sharing console output or simple HTML reports often does not provide enough details or context for working together on fixing and analyzing problems.
Visual Studio Code is a popular tool for developers. But it doesn’t have good options for detailed test reporting. It is great for editing and fixing code. However, it does not show test results clearly. That’s where Allure comes in. Allure does a great job with test reporting.
Allure reports help solve these problems. They present information clearly and visually, which makes sharing easy. You can make Allure reports fast with simple commands. This helps everyone, whether they are technical or not, to use them easily.

The Importance of Detailed Test Reports

A test report is really important. It gives a clear view of what happened during a test run. The report should include more than just the test cases and their results. A good report will also explain why the results happened.
Allure results make things easier. You can group tests by features, user stories, or Gherkin tags. This detail helps you check and share information better. It allows you to track the progress and quality of different parts of your application.
You can add screenshots, videos, logs, and custom data to your test reports. For example, if a test fails, your report can include a screenshot of the app at the time of the failure. It can also display important log messages and network requests from the test. This extra information helps developers find problems faster and saves time when fixing issues.

Introducing Allure Report: A Solution to WebdriverIO Reporting Woes

Enter Allure Report. This is a free tool for reporting. It is easy to use and strong enough for your needs. Allure works well with WebdriverIO. It turns your raw test data into nice and engaging reports. You don’t have to read through long lines of console output anymore. Now, you can enjoy clear test reports.
Allure is different from other reporting tools. It does not just give you a simple list of tests that passed or failed. It shows a clear and organized view of your test run. This lets you see how your tests work together. You can spot patterns in errors and get helpful insights about your application’s performance.

Key Benefits of Integrating Allure with WebdriverIO

Integrating Allure with WebdriverIO is easy. You just need to use the Allure WebdriverIO adapter. First, install the npm packages. Next, add a few setup lines to your WebdriverIO project. With Allure, you can change its configuration without hassle. This means you can modify how your reports appear and control the level of detail in them.
Here are some key benefits:

  • Clear and Organized Reports: Allure reports show your tests in a clear way. They have steps, attachments, timing, and info about the environment.
  • Easy-to-Understand Visuals: Allure displays your results in a fun and simple manner. This helps you analyze data and spot trends fast.
  • Better Teamwork: Allure gives tools like testing history and linking issues. This helps developers, testers, and stakeholders work together better.

These benefits speed up testing and make it better.

Overview of Allure’s Features and Capabilities

The Allure Report is great because it can fulfill many reporting needs. If you need a quick summary of your tests or a close look at one test case, Allure has it. It helps you keep your tests organized. You can sort them by features, stories, or any other way you like.
This organization is designed to be simple and user-friendly. For example, a team member can easily find tests that are failing for a certain feature. This allows them to choose which bugs to fix first. They can also understand how these fixes will impact the entire application.
Let’s look at the main features of Allure for WebdriverIO:

Feature Description
Detailed Test Results Provides comprehensive details for each test case, including steps, attachments, logs, and timings.
Hierarchical Organization Enables grouping and categorizing tests based on features, stories, or other criteria for better organization.
Screenshots & Attachments Allows attaching screenshots, videos, logs, and other files to test cases for easier debugging and analysis.
Customizable Reports Offers flexibility in customizing the appearance and content of the report to meet specific needs.
Integration with CI/CD Tools Seamlessly integrates with popular CI/CD tools, allowing for automated report generation and distribution.
Historical Data & Trends Tracks historical test data, enabling the identification of trends and patterns in test results over time.
Output Directory After each test run, Allure generates a directory (customizable) containing all the report data, ready to be served by the Allure command-line tool.

Step-by-Step Guide to Integrating Allure Report with WebdriverIO

Ready to improve your WebdriverIO reports using Allure? Let’s go through the simple setup process step by step. We will discuss the basic setup and how to customize it for your needs. The steps are easy, and the benefits are fantastic. By the end of this guide, you will know how to create helpful Allure reports for your WebdriverIO projects.
We will learn how to install packages. We will also examine configuration files. Get ready to discover the benefits of good test reporting.

Prerequisites

Make sure you have Node.js installed. Create a new WebdriverIO project if you don’t have one.

npm init wdio .

During this setup, WebdriverIO will generate a basic project structure for you.

Step 1: Install Dependencies

To integrate Allure with WebdriverIO, you need to install the wdio-allure-reporter plugin:

npm install @wdio/allure-reporter --save-dev
npm install allure-commandline --save-dev

Step 2: Update WebdriverIO Configuration

In your wdio.conf.js file, enable the Allure reporter. Add the reporter section or update the existing one:


js
Copy code
exports.config = {
  // Other configurations...
  reporters: [
    ['allure', {
      outputDir: 'allure-results', // Directory where allure results will be saved
      disableWebdriverStepsReporting: false, // Set to true if you don't want webdriver actions like clicks, inputs, etc.
      disableWebdriverScreenshotsReporting: false, // Set to true if you don't want to capture screenshots
    }]
  ],

// The path of the spec files will be resolved relative from the directory of
    // of the config file unless it's absolute.
    //
    specs: [
        './test/specs/webdriverioTestScript.js'
    ],
 // More configurations...
}

Step 3: Example Test with Allure Report

Here’s a sample WebdriverIO test that integrates with Allure:


const allureReporter = require('@wdio/allure-reporter').default;
 describe('Launch_Application_URL', () => {
    it('Given I launch "Practice Test Automation" Application', async () => {
        allureReporter.addFeature('Smoke Suite :: Practice Test Automation Application'); // Adds a feature label to the report
        allureReporter.addSeverity('Major'); // Marks the severity of the test
        allureReporter.addDescription('Open Google and perform a search for WebdriverIO');
       
        await browser.url('https://practicetestautomation.com/practice-test-login/');

        allureReporter.addStep('Given I launch Practice Test Automation Application');
        var result = await $('//h2[text()="Test login"]');
        await expect(result).toBeDisplayed();
});
});
describe('Login_Functionality', () => {
    it('When I login with valid Credential', async () => {
const txtUsername = await $('#username');
await txtUsername.setValue('student');
allureReporter.addStep('Enter Username : student');
const txtPassword = await $('#password');
await txtPassword.setValue('Password123');
allureReporter.addStep('Enter Password : Password123')
const btnLogin = await $('//button[@id="submit"]');
     
     await btnLogin.click();
        allureReporter.addStep('Click Login Button');
});
});
describe('Verify_Home_Page', () => {
    it('Then I should see Logged In successfully Message', async () => {
        const result = await $('//h1[text()="Logged In Successfully"]');
        await expect(result).toBeDisplayed();
        allureReporter.addStep('Then I should see Logged In successfully Message');
});
});

In this test:

  • allureReporter.addFeature(‘Feature Name’) adds metadata to the report.
  • addStep() documents individual actions during the test.

Step 4: Run Tests and Generate Allure Report

1.Run the tests with the command:

npx wdio run ./wdio.conf.js

This will generate test results in the allure-results folder.

2.Generate the Allure report:

npx allure generate allure-results --clean

3.Open the Allure report:

npx allure open

ALTTEXT

This will open the Allure report in your default web browser, displaying detailed test results.

ALTTEXT

Note : If you want to generate a allure report in a single html file, follow below steps

  • Open cmd for framework location
  • enter “allure generate –single–file D:\QATest\WebdriverIO-JS\allure-results”

ALTTEXT

It will generate single html file in “allure-report” folder as below.

ALTTEXT

Step 5: Adding Screenshots

You can configure screenshots to be captured on test failure. In the wdio.conf.js, ensure you have the afterTest hook set up:

 afterTest: async function(test, context, { error, result, duration, passed, retries }) {
            await browser.takeScreenshot();
    },

Elevating Your Reporting Game with Allure

The best thing about Allure is how simple it is to customize. It is more than just a standard reporting tool. Allure lets you change your reports to fit your project’s needs. You can also change how Allure operates by editing your wdio.conf.js file. This will help it match your workflow just right.
You can make your reports better by adding key details about the environment. You can also make custom labels for easier organization and connect with other tools. Check out advanced features like adding test attachments. For example, if you want to take a screenshot during your test, you can use Allure’s addAttachment function. This function allows you to put useful visual info straight into your report.

Customizing Reports for Comprehensive Insights

You can do much more with Allure than just setting it up. You can change your reports by adding metadata right in your test code. With Allure’s API, you can add details like features, stories, and severity levels to your tests. This metadata gives useful information for your reports.
You might want to mark some tests as important or organize them by user stories. You can do this easily with Allure’s API. It makes your reports look better and feel better. Just think about being able to filter your Allure report to see only the tests related to a specific user story planned for the next release.
Adding metadata like severity helps your team concentrate on what is important. This change turns your reports from just summaries into useful tools for making decisions. You can explore Allure’s addLabel, addSeverity, and other API features to make the most of customized reporting.

Tips and Tricks for Advanced Allure Reporting Features

Let’s improve our Allure reporting with some helpful tips. Using Allure with WebdriverIO makes it even better. For example, you can use the takeScreenshot function from WebdriverIO along with Allure. By capturing screenshots at important times during your tests, like when there is a failure or during key steps, you can add pictures to your reports.
Allure’s addArgument function is really helpful. It helps you remember important details that can help with debugging. For example, when you test a function using different inputs, you can use addArgument to record those inputs and the results. This makes it easier to connect failures or strange behavior to specific inputs.
Remember to use Allure’s command-line interface (CLI) to create and view your reports on your computer. After running your tests and when your allure-results directory is full, go to your project root in your terminal. Then, type these commands:
allure generate allure-results –clean
allure open
This will make your report and open it in your default browser. It’s easy!

Conclusion

Using the Allure Report with WebdriverIO can make your testing better. You will receive clear test reports that provide useful information. There are many advantages to adding Allure. It lets you change how your reports look and use special tools. Connecting Allure with WebdriverIO is easy; just follow a simple guide. This strong tool can fix common reporting issues and improve your testing. With Allure, you will easily see all your test results. This helps you to make smart choices for your projects. Use Allure’s helpful features to improve your reports and make your testing a success.

Frequently Asked Questions

  • How Can I Customize Allure Reports to Fit My Project Needs?

    Customization is very important in Allure. You can change the settings in the Allure reporter by updating your wdio.conf.js file. This lets you choose where the allure-results folder will be located and how to arrange the results. You can also include metadata and attachments directly in your test code. This way, you can create reports that meet your needs perfectly.

  • What Are the Common Issues Faced While Integrating Allure with WebdriverIO and How to Resolve Them?

    To fix issues with Allure integration, start by checking if you have installed the Allure CLI and the WebdriverIO plugin (@wdio/allure-reporter) using npm. Next, ensure that your wdio.conf.js file has the right settings for the Allure reporter.

Streamlining Automated Testing with Github Actions

Streamlining Automated Testing with Github Actions

Automated testing plays a big role in software development today. GitHub Actions is a useful tool for continuous integration (CI). When developers use GitHub Actions for automated testing, it makes their testing processes easier. This leads to better code quality and helps speed up deployment.

Key Highlights

  • Learn how to automate your testing processes with GitHub Actions. This will make your software development quicker and better.
  • We will help you set up your first workflow. You will also learn key ideas and how to use advanced features.
  • This complete guide is great for beginners and for people who want to enhance their test automation with GitHub Actions.
  • You can see practical examples, get help with issues, and find the best ways to work. This will help you improve your testing workflow.
  • Discover how simple it is to connect with test management tools. This can really boost your team’s testing and reporting skills.

Understanding GitHub Actions and Automated Testing

In software development, testing is very important. Test automation helps developers test their code fast and accurately. When you use test automation with good CI/CD tools, like GitHub Actions, it improves the development process a lot.
GitHub Actions helps teams work automatically. This includes test automation. You can begin automated tests when certain events happen. For example, tests can run when someone pushes code or makes a pull request. This ensures that every change is checked carefully.

The Importance of Automation in Software Development

Software development should happen quickly. This is why automation is so important. Testing everything by hand each time there is a change takes a long time. It can also lead to mistakes.
Test automation solves this issue by running test cases without help. This allows developers to focus on other important tasks. They can spend time adding new features or fixing bugs.
GitHub Actions is a powerful tool. It helps you to automate your testing processes. It works nicely with your GitHub repository. You can run automated tests each time you push changes to the code.

Overview of GitHub Actions as a CI/CD Tool

GitHub Actions is a strong tool for CI and CD. It connects well with GitHub. You can design custom workflows. These workflows are groups of steps that happen automatically when certain events take place.
In continuous integration, GitHub Actions is very helpful for improving test execution. It allows you to automate the steps of building, testing, and deploying your projects. When you make a change in the code and push it to your new repository’s main branch, it can kick off a workflow that will, by default, run tests, including any related to Pull Requests (PR), build your application, and deploy it either to a staging area or to production.
This automation makes sure your code is always checked and added. It helps to lower the chances of problems. This also makes the development process easier.

Preparing for Automated Testing with GitHub Actions

Before you start making your automated testing workflow, let’s make sure you have everything ready. This will help your setup run smoothly and be successful.
You need a GitHub account. You also need a repository for your code. It helps to know some basic Git commands while you go through this process.

What You Need to Get Started: Accounts and Tools

If you don’t have a repository, start by making a new one in your GitHub account. This repository will be the main place for your code, tests, and workflow setups.
Next, choose a test automation framework that suits your project’s technology. Some popular choices are Jest for JavaScript, pytest for Python, and JUnit for Java. Each option has a unique way of writing tests.
Make sure your project has the right dependencies. If you use npm as your package manager, run npm ci. This command will install all the necessary packages from your package.json file.

Configuring Your GitHub Repository for Actions

With your repository ready, click on the “Actions” tab. Here, you can manage and set up your workflows. You will organize the automated tasks right here.
GitHub Actions searches for files that organize workflows in your repository. You can locate these files in the .github/workflows directory. They use YAML format. This format explains how to carry out the steps and gives instructions for your automated tasks.
When you create a new YAML file in this directory, you add a new workflow to your repository. This workflow begins when certain events happen. These events might be code pushes or pull requests.

Creating Workflow on GitHub Actions

Pre-Requisites:

  • Push the “Postman” collection and “Environment” file in repository.
  • Install “Newman” in your system.

Create a new workflow:

  • Open your GitHub repository.
  • Click on the “Actions” tab on the top.
  • Click on “New workflow” in the actions page.
  • Click on “Configure” button within “Simple Workflow” in “New workflow” page.
  • You can navigate to the “.github/workflow” directory , where we can configure the default “blank.yml” file.
  • Based on the requirements we can configure the “.yml” file, for example if you want to triggers a particular branch whenever the deployment is done, we need to “configure” the branch name in the “.yml” file.
  • We can configure the workflow to be triggered based on specific events, such as whenever a push or pull request occurs in the specified branch.
  • ALTTEXT

  • Add steps to install NodeJS and Newman in the .yml file
  • ALTTEXT

  • If you want to run the particular collection in your branch, configure the “.yml” file using the below command:
  • ALTTEXT

  • To generate an HTML report, you must include steps to install the htmlextra dependency and establishing a folder to store the report.

The screenshot below demonstrates creating a folder to save the report:

ALTTEXT

The screenshot below illustrates copying the generated HTML report:

ALTTEXT

  • Once the configuration setup is completed click on “Commit changes”
  • ALTTEXT

  • Create a new branch and raise an “PR” to the appropriate branch where you want the workflow.
  • Accept the “PR” from the respective branch.
  • After the “Workflow” is added (or) merged in the respective branch, it will auto trigger the configured file (or) folder every time whenever the deployment is done.

Report Verification:

  • Once the execution is completed, we can see the report in the “Actions” tab.
  • The recent executions are displayed at the top (or) the recent workflows are displayed in the left side of the “Actions” panel.
  • Click on the “Workflow”.
  • Click on “build” where we can see the entire test report.
  • The “html” report is generated under “Artifacts” at the bottom of the workflow run.
  • ALTTEXT

  • When you click on the report, it will be getting download in your local system as a zip file.

Issues Faced:

  • Sometimes the htmlextra report will not be generated if any of the previous steps or any of the tests getting failed in your postman collection, to handle this error we need to handle the issue.
  • To fix the issue we need to handle it with the “if” condition.

ALTTEXT

Enhancing Your Workflow with Advanced Features

Now that you have a simple testing workflow set up, let’s look at how we can make it better. We can improve it by using advanced features from GitHub Actions.
These features let you run tests at the same time. They also help speed up build times. This can make your CI/CD pipeline easier and faster.

Incorporating Parallel Testing for Efficiency

As your test suite gets bigger, it takes more time to run UI tests. GitHub Actions can help make this easier. It allows you to run your new configuration tests in parallel, which is a great way to cut down the time needed for your tests. By breaking your test suite into smaller parts, you can use several runners to run these parts simultaneously and you can even use a test automation tool to subscribe to notifications about the test run ID and the progress.
This helps you receive feedback more quickly. You don’t need to wait for all the tests to end. You can gain insights into certain parts fast.

Here are some ways to use parallel testing:

  • Split by Test Files: Divide your test suite into several files. You can set up GitHub Actions to run them all together.
  • Split by Test Types: If you group your tests by type, like unit, integration, or end-to-end, run each group together.
  • Use a Test Runner with Parallel Support: Some test runners can run tests at the same time. This makes it easier to set up.

Utilizing Cache to Speed Up Builds

Caching is important in GitHub Actions. It helps speed up your build processes. When you save dependencies, build artifacts, or other files that you use often, it can save you time. You won’t have to download or create them again.
Here are some tips for using caching:

  • Find Cachable Dependencies: Look for dependencies that do not change. You can store them in cache. This means you will not need to download them again.
  • Use Actions That Cache Automatically: Some actions, like actions/setup-node, have built-in caching features. This makes things easier.
  • Handle Cache Well: Make sure to clear your cache regularly. This helps you save space and avoid problems from old files.

Monitoring and Managing Your Automated Tests

It is important to keep an eye on the health and success of automated tests. This is as important as creating them. When you understand the results of the workflow, you can repair any tests that fail. This practice helps to keep a strong CI pipeline.
By paying close attention and taking good care of things, you can make sure your tests give the right results. This helps find and fix any problems quickly.

Understanding Workflow Results and Logs

GitHub Actions helps you see each workflow run in a simple way. It shows you the status of every job and step in that workflow. You can easily find this information in the “Actions” tab of your repository.
When you click on a specific workflow run, you can see logs for each job and step. The logs show the commands that were used, the results they produced, and any error messages. This information is helpful if you need to solve problems.
You might want to connect to a test management tool. These tools can help you better report and analyze data. They can show trends in test results and keep track of test coverage. They can also create detailed reports. This makes your test management much simpler.

Debugging Failing Tests and Common Issues

Failing tests are common. They help you see where your code can get better. It is really important to fix these failures well.
Check the logs from GitHub Actions. Focus on the error messages and stack traces. They often provide helpful clues about what caused the issue.
Here is a table that lists some common problems and how to fix them:

Issue Troubleshooting Steps
Test environment misconfiguration Verify environment variables, dependencies, and service configurations
Flakiness in tests Identify non-deterministic behavior, isolate dependencies, and implement retries or mocking
Incorrect assertions or test data Review test logic, data inputs, and expected outcomes

Conclusion

In conclusion, using automated testing with GitHub Actions greatly enhances your software development process by improving speed, reliability, and efficiency. Embracing automation allows teams to streamline repetitive tasks and focus on innovation. Tools like parallel testing further optimize workflows, ensuring code consistency. Regularly monitoring your tests will continuously improve quality. If you require similar automation testing services to boost your development cycle, reach out to Codoid for expert solutions tailored to your needs. Codoid can help you implement cutting-edge testing frameworks and automation strategies to enhance your software’s performance.

Frequently Asked Questions

  • How Do I Troubleshoot Failed GitHub Actions Tests?

    To fix issues with failed GitHub Actions tests, look at the logs for every step of the job that failed. Focus on the error messages, stack traces, and console output. This will help you find the main problem in your code or setup.

Playwright Cheatsheet: Quick Tips for Testers

Playwright Cheatsheet: Quick Tips for Testers

Playwright is an incredibly popular and powerful tool for end-to-end automation testing of modern web applications. It offers great advantages such as faster execution speed, great documentation, and a slew of built-in features for reporting, debugging, parallel execution, and so on. If you are thinking about building your test automation framework with Playwright or migrating from a different tool, our comprehensive Playwright Cheatsheet will help you get started with the tool quickly. As an experienced automation testing service provider, we have used Playwright in our projects for different needs and we have covered some of Playwright’s most unique and advanced methods, designed to make your testing and automation processes more efficient and effective.

Playwright Cheatsheet

We have structured our Playwright Cheatsheet in a way that it is easy for both beginners to learn and experts to quickly refer to some important snippets they might be looking for.

Basic Commands

Advanced Interactions

Browser, Context Management

First up in our Playwright Cheatsheet, we’re going to start with the basics to see how to launch a browser instance in regular mode, incognito mode, and so on.

1. Launching a Browser Instance
  • chromium.launch(): Initiates a new instance of the Chromium browser.
  • browser.newContext(): Establishes a fresh browser context, which represents an incognito mode profile.
  • context.newPage(): Generates a new browser tab (page) within the context for interaction.
// Step 1: Initiate a new instance of the Chromium browser
  const browser = await chromium.launch({ headless: false });
  // Step 2: Establish a fresh browser context
  const context = await browser.newContext();
  // Step 3: Generate a new browser tab within the context
  const page = await context.newPage();
2. Creating a Persistent Context

You can use persistent contexts to maintain session continuity and reuse authentication states across tests. It allows for testing scenarios where user sessions need to be preserved.

// Launch a persistent context using the specified user data dir
const context = await chromium.launchPersistentContext(userDataDir, {headless: false });

Selectors & Mouse Interactions

Once the browser instance has been launched, the next steps in the automation will involve keyboard and mouse interactions which we will be seeing now in our Playwright Cheatsheet.

1. Using Selectors for Element Interaction
  • page.goto(): Directs the browser tab to a specified URL.
  • page.click(): Locates and triggers a button with the identifier Example: ‘submit’.
  • page.fill(): Finds an input field with the name ‘username’ and inputs the value.
  • page.selectOption(): Identifies a dropdown menu and chooses the option.
await page.goto('https://example.com');
await page.click('button#submit');
await page.fill('input[name="username"]', 'example_user');
await page.selectOption('select[name="city"]', 'New York');

Checkboxes and Radio Buttons: Easily toggle checkboxes and radio buttons using locator.setChecked() in Playwright. This method simplifies the process of both selecting and deselecting options.

// Step 3: Locate a checkbox using its label
const checkbox = page.getByLabel('Terms and Conditions');
// Ensure the checkbox is checked
await checkbox.setChecked(true);
// Step 4: Assert that the checkbox is checked
await expect(checkbox).toBeChecked();

type() : The type method in Playwright is used to simulate keyboard input into a text input field, text area, or any other element that accepts text input.

 await page.getByPlaceholder('Enter your name').type('John Doe');

press(): The press method in Playwright is used to simulate pressing a key on the keyboard. This method allows you to automate keyboard interactions with web pages.

await page.keyboard.press("Enter");

title(): The title method in Playwright is used to retrieve the title of the current web page. You can use this method to extract the title of the web page you are interacting with during your automation or testing scripts.

const pageTitle = await page.title();
console.log(`page title is : ${pageTitle});

check(): The check method in Playwright is used to interact with checkboxes and radio buttons on a web page.

await page.check('input#myCheckbox');
               Or
await page.locator('input#myCheckbox').check();

unCheck(): The uncheck method in Playwright is used to uncheck (deselect) checkboxes or radio buttons on a web page.

await page.uncheck('input#myCheckbox');
                Or
await page.locator('input#myCheckbox').uncheck();

focus(): This method can be particularly useful when you want to simulate user interactions like keyboard input or navigating through a web application using keyboard shortcuts.

await page.locator('input#username').focus();

hover(): The hover method in Playwright is used to simulate a mouse hover action over a web page element. When you hover over an element, it can trigger various interactions or reveal hidden content.

await page.locator('button#myButton').hover();
                or
await page.hover('button#myButton');

textContent(): Although the textContent method is not a built-in method in Playwright, it is a standard JavaScript method used to retrieve the text content of a DOM element.

const element = await page.locator('div#myElement'); 
const textContent = await
 element.textContent()console.log('Text Content:', textContent);

allTextContents(): In Playwright, the allTextContent method is used to find array of multiple elements in the DOM. which returns an array of textContent values for all matching nodes.

const element = page.locator('div#Element');
const textContents = await element.allTextContents();
console.log(`All Text Contents : ${textContents}`);

inputValue(): The inputValue method in Playwright is used to retrieve the current value of an input element, such as a text input, textarea, or password field.

 // Using inputValue to retrieve the current value of the input field
 const inputValue = await page.inputValue('input#username');
 console.log('Current input value:', inputValue);

close(): The close method is the last selector we’re going to see in our Playwright cheatsheet and it is used to close a browser, browser context, or page. You can use this method to gracefully shut down browser instances or specific pages. Here’s how you can use the close method in Playwright.

 // Close the page when done
     await page.close();
 // Close the browser context
      await context.close();
 // Close the browser instance
      await browser.close();
2. Mouse Interactions

Clicks and Double Clicks: Playwright can simulate both single clicks and double clicks on elements.

 // Single click
await page.click('selector');
// Double click
await page.dblclick('selector');

Hover and Tooltips: You can use Playwright to hover over elements and reveal tooltips or activate dropdown menus.

await page.hover('selector');
const tooltip = await page.waitForSelector('tooltip-selector');
const tooltipText = await tooltip.innerText(); // Get text from the tooltip
console.log(tooltipText);

Drag and Drop: Here are the Playwright techniques for simulating drag-and-drop interactions between elements on a webpage.

// Locate the source and target elements
const source = await page.$('source-selector');
const target = await page.$('target-selector');
// Perform drag-and-drop
await source.dragAndDrop(target);

move(): mouse.move(x, y) in Playwright is used to move the mouse to a specific position on the page. This can be useful for simulating mouse movements during automated testing. The x and y parameters represent the coordinates where you want the mouse to move, with (0, 0) being the top-left corner of the page.

await page.mouse.move(100, 100);

dragTo(): This method is useful for automating drag-and-drop interactions in your web application. Let’s see how to use the dragTo() method with a sample snippet in our Playwright cheatsheet.

//Locate the source and target elements you want to drag & drop
const sourceElement = await page.locator('source-element-selector')
const targetElement = await page.locator('target-element-selector')  
// Perform the drag-and-drop action
await sourceElement.dragTo(targetElement)

Pressing and Releasing Mouse Buttons: In Playwright, you can simulate pressing and releasing mouse buttons using the mouse.down() and mouse.up() methods.

const myElement = page.locator('.my-element')
await myElement.mouse.down()  // Press the left mouse button    
await myElement.mouse.up()   // Release the left mouse button

Context Menu: See how Playwright interacts with context menus by right-clicking elements and selecting options.

// Right-click on an element to open the context menu
await page.click('element-selector', { button: 'right' });
// Wait for the context menu to appear
await page.waitForSelector('context-menu-selector', { state: 'visible' });
// Click on an option within the context menu
await page.click('context-menu-option-selector');

Scrolling: Discover how to simulate scrolling actions in Playwright using mouse interactions. Demonstrate scrolling through a long webpage to ensure all content loads correctly or to capture elements that only appear when scrolled into view.

// Click on an option within the context menu
await page.click('context-menu-option-selector');
await page.evaluate((x, y) => { window.scrollBy(x, y); });

Note: Use stable selectors like IDs or data attributes to ensure robust tests; validate mouse interactions by asserting resulting UI changes.

Locators

As we all know, a locator is a tool for locating elements on a webpage and Playwright has a lot of available locators. Now in our Playwright cheatsheet, we’re going to see the several available methods for finding elements, and the chosen parameters are sent to the methods for finding elements.

1. getByRole(): getByRole is used to query and retrieve elements on a web page based on their accessibility roles, such as “button,” “link,” “textbox,” “menu,” and so on. This is particularly useful for writing tests that focus on the accessibility and user experience of a web application.

getByRole

// Click on an option within the context menu
await page.getByRole('textbox', {name:'Username'}).fill(‘vijay’);

2. getByText(): Although getByText() is not a built-in method in Playwright, it is a method that is often used in testing libraries like Testing Library (e.g., React Testing Library or DOM Testing Library) to query and interact with elements based on their text content.

getByText

await page.getByText('Forgot your password? ').click();

3. getByPlaceholder(): The getByPlaceholderText method is used to select a DOM element based on its placeholder attribute in an input element.

getByPlaceholder

await page.getByPlaceholder('Username').fill('vijay');

4. getByAltText(): getByAltText() is not a method associated with Playwright; it’s actually a method commonly used in testing libraries like React Testing Library and Testing Library (for various JavaScript frameworks) to select an element by its alt attribute. If you are writing tests using one of these testing libraries, here’s how you can use getByAltText().

getByAltText

await page.getByAltText('client brand banner').isVisible();

5. getByTitle() :getByTitle() method in Playwright is for interacting with an HTML element that has a specific title attribute.If you are writing tests using one of the testing libraries mentioned above, here’s how you can use it

getByTitle

  await page.getByTitle('Become a Seller').click();

File and Frame Handling

As we have seen how to launch the browser instance, use selectors, and handle mouse interactions in our Playwright cheatsheet, the next step would be to see how we can handle files, frames, and windows. Let’s start with files and frames now.

1. Handling File Uploads
  • Easily handle file uploads during testing to ensure the functionality works as expected in your application by referring to the below code.
     // Navigate to the page with the file upload form
    await page.goto('your-page-url');
    // Trigger the file input dialog
    const [fileChooser] = await Promise.all([page.waitForEvent('filechooser'),
    page.click('button-to-trigger-file chooser')]);
    // Set the files to upload
    await fileChooser.setFiles('path/to/your/file.txt');
    
    2. Interacting with Frames
  • Playwright allows you to interact with frames on a web page using methods like frame(), frames(), and waitForLoadState(). Here’s how you can do it.
  • Use the frame() method to access a specific frame by its name, URL, or element handle.
  • Get Frame using Name FrameSelector :
     const allFrames = page.frames();
    
  • Get Frame using Name Option :
    const myFrame = page.frame({name: "frame1"}); 
                  or
    const myFrame = page.frame("frame1");
    
  • Get Frame using URL option :
    const 
    Myframe=page.frame({url:"http://autopract.com/playwright/form1/"});
    
  • Get Frame using Selector :
    const
    myFrame = page.frameLocator("iframe[name='frame1']");
    
  • Navigate within a specific frame using the goto() method.
    await frame.goto('https://codoid.com');
    
  • Go back and forward within a frame using the goBack() and goForward() methods
    await frame.goBack();
    await frame.goForward();
    
  • Wait for a frame to load or reach a specific load state using the waitForLoadState() method.
await frame.waitForLoadState('domcontentloaded');

Best Practices:

Automate file uploads and downloads to streamline file-related workflows. You can switch between frames using IDs or names for seamless interaction.

Windows Handling

Windows handling is an important aspect of web automation and testing, especially when dealing with scenarios where you need to interact with multiple browser windows or tabs. And that is why we have covered it in our Playwright Cheatsheet.

Playwright provides methods for handling multiple browser windows and tabs within a single browser instance. Here’s how you can work with windows handling in Playwright.

 const [newWindow] = await Promise.all([context.waitForEvent('page'),
  await page.getByText('APPLE iPhone 14 (Blue, 128  GB)').first().click()]);
  await newWindow.waitForLoadState();
  expect(newWindow.url()).toContain('apple-iphone-14');
  • To switch to a specific window or tab using the page title or URL:
     const secondPage = pages.find((page) => page.url()==='https://codoid.com');
       await secondPage.bringToFront();
    
  • Close a specific window/tab when you are done with it:
    await secondPage.close();

Best Practices:

Manage multiple windows or tabs by tracking handles and switching context as necessary. Make sure to close windows or tabs after tests to maintain a clean testing environment.

Special Capabilities

As stated earlier in our Playwright Cheatsheet, we have also covered advanced interactions in addition to the basic commands. The first of the many advanced interactions we’re going to see special capabilities such as device emulation and record and playback capabilities.

1. Emulating Devices:

  • You can emulate a device for responsive testing to ensure your app looks good on various devices. This is crucial for testing mobile responsiveness and user experience.
 const { devices, chromium } = require('playwright');
// Define the device you want to emulate
const iPhone = devices['iPhone 11'];
// Launch a browser and create a new context with device emulation
const browser = await chromium.launch();
const context = await browser.newContext({...iPhone,});

2. Recording and Replaying Actions

  • You can automatically generate Playwright scripts with ease by recording your actions within a browser. This speeds up the creation of test scripts by capturing real user interactions.
npx playwright codegen
 

Network Interception and Manipulation

Testing is not just about validating the results with happy paths as users might face numerous challenges in real-world scenarios. One of the common challenges can be with the network and we can manipulate it based on our testing needs. Let’s see how in our Playwright Cheatsheet.

1. Mocking Responses

Intercept and mock network responses to evaluate your app’s handling of different API responses. This is useful for testing error scenarios and verifying API integrations.

// Intercept requests to a specific URL
 await page.route('**/api/data', async (route) => {
// Respond with custom data
  await route.fulfill({
  contentType: 'application/json',
  body: JSON.stringify({ key: 'mockedValue' }) }); });
 

2. Simulating Offline Mode

Test how your application behaves when offline by simulating network disconnections. This ensures that your app handles offline scenarios seamlessly.

  // Set the page to offline mode
  await page.setOffline(true);
  // Navigate to a page and perform actions
  await page.goto('https://example.com');
  // Restore network connection (optional)
  await page.setOffline(false);
 

Screenshots and Visual Comparisons

Screenshots play a vital role in terms of reporting and with Playwright, you have the provision of capturing full-page screenshots and also screenshots of a particular element if required.

1. Screenshots

Capturing a Full-Page Screenshot

  • You can take a screenshot of the entire page to visually verify the UI. This is beneficial for visual regression testing to identify unexpected changes.
 // Take a full-page screenshot
await page.screenshot({ path: 'fullpage-screenshot.png', fullPage: true});
 

  • There is also a provision to capture a screenshot of a specific element to focus on individual UI components. It helps in verifying the appearance of particular elements.
// Locate the element
 const element = await page.$('selector-for-element');
 if (element) {
// Take a screenshot of the element
 await element.screenshot({ path: 'element-screenshot.png' });
 console.log('Element screenshot taken'); }
 

Debugging and Tracing

The next set of advanced interactions we’re going to see in our Playwright cheatsheet is the debugging and tracing features that enable easier debugging and failure analysis/

Enabling Debug Mode(SlowMo)
  • Using Playwright, you can execute tests in a visible browser with slow motion enabled for easier debugging. This helps you see what’s happening in real time and diagnose the issues.
// Launch the browser with slowMo
  const browser = await chromium.launch({
    headless: false, // Run in headful mode to see the browser
    slowMo: 1000 // Slow down actions by 1000 milliseconds (1 second)
  });
Capturing Traces
  • You can capture detailed traces to analyze test failures and performance issues. This offers insights into test execution for debugging purposes.
  // Start tracing
  await context.tracing.start({ screenshots: true, snapshots: true });
const page = await context.newPage();
await page.goto('https://example.com');
// Perform actions
 await page.click('selector-for-button');
 await page.fill('selector-for-input', 'some text');
// Stop tracing and save it to a file
 await context.tracing.stop({ path: 'trace.zip' });

Best Practices:

You can also use console logs and debug statements within tests to troubleshoot issues and enable tracing to capture detailed logs for performance analysis.

Additional Methods

In the final section of our Playwright cheatsheet, we are going to see a few additional methods such as retrying actions, using locator assertions, and forcing colors mode.

Retrying Actions

Retrying actions addresses intermittent issues by repeatedly attempting a failed action until it either succeeds or the maximum number of retries is exhausted.

 const retryDelay = 1000; const maxRetries = 3; // 1 second delay between retries
 await new Promise(resolve => setTimeout(resolve, retryDelay)); // Delay before retrying

Using Locator Assertions

  • You can add assertions to ensure elements are visible, improving test reliability. This verifies that critical elements are present on the page.
 // Check if the element is visible
await expect(page.locator('selector-for-element')).toBeVisible();
  • Enabled/Disabled State Assertions
    await expect(page.locator('selector-for-element')).toBeEnabled();
    await expect(page.locator('selector-for-element')).toBeDisabled();
    
  • Text and Count Assertion
    await expect(page.locator('selector-for-element')).toHaveText('Expected Text');
    await expect(page.locator('selector-for-elements')).toHaveCount(expectedCount);
    
  • Invisibility Assertion
await expect(page.locator('selector-for-element')).toBeHidden();

Forcing Colors Mode

  • There is even an option to simulate the high contrast mode for accessibility testing, ensuring usability for all users. This is crucial for testing the accessibility features of your application.
// Force dark color scheme
await page.emulateMedia({ forcedColors: 'dark' });
await browser.close(); })();

Conclusion

Playwright offers an extensive set of features that go beyond basic browser automation. Whether you’re testing complex user interactions, simulating various devices and network conditions, or capturing detailed traces for debugging, Playwright equips you with the tools you need to create reliable and efficient tests. We hope our Playwright cheatsheet will be helpful for you to use all these features with ease.

A Quick Playwright Overview for QA Managers

A Quick Playwright Overview for QA Managers

Playwright is an automation testing tool that has been gaining a lot of traction in the QA community. Despite being the latest tool compared to Selenium and Cypress, Playwright has become a popular choice today. Being a QA manager, you might be in the position to choose an automation tool for your testing needs or might be considering migrating to a different technology to better suit your needs. During such a scenario, you’ll have a lot of questions in your mind that you will be searching for answers to. In this Playwright overview blog, we’re going to answer all those questions as our prospective clients ask similar questions during introductory or discovery calls for our test automation services.

Common Playwright Questions

Before we head over to the answers, let’s first list out all the commonly asked questions that we will be addressing.

If an automation tester is fond of a particular tool, they will likely promote it to their colleagues and acquaintances. Nonetheless, we must evaluate the pros and cons before suggesting an automation testing tool. Let us examine each question’s solutions individually in our Playwright overview blog.

1. What is the difference between Cypress and Playwright?

Cypress is a web application automation testing tool and it differs from Selenium in one fundamental aspect. Selenium sends a command to a browser via JSON wire protocol and calls the browser API to perform an action on the application. However, in Cypress, your test code can access all the application’s objects like your product code since it runs the tests inside of the browser.

Advantages of running tests inside the browser:

  • You can alter web traffic on the fly
  • You can modify everything coming in & out of the browser
  • Faster execution
  • No need to add additional wait commands
  • Enable advanced debugging facilities

Now let’s take a look at Playwright. It is also a framework to automate web applications and it achieves all the features of Cypress without using in-process test runner. Currently, Playwright is a popular choice among testers due to its quick test execution and compatibility with all modern browsers. It also supports multiple languages such as JavaScript, TypeScript, Python, C#, and Java for writing the tests. On the other hand, Cypress only supports JavaScript as its scripting language.

2. What programming language can I choose for Playwright?

You can select the appropriate scripting language according to your team’s familiarity and proficiency. The core features and implementations of Playwright are consistent across all supported languages.

To assess the release information for each language, simply refer to the corresponding GitHub repository for that language’s implementation.

3. Advantages of Playwright?

Although we are viewing the advantages throughout the Playwright overview blog, we have listed the key aspects for you to get a quick understanding.

  • Playwright is a reliable & e2e automation testing framework for modern web apps
  • It works with Chromium, Chrome, Edge, Firefox, & WebKit
  • Works on any platform
  • You can execute the tests in full isolation
  • Test Execution is super fast
  • Supports Headless and Headful modes
  • Playwright is much faster than Cypress, Selenium, WebDriverIO, & Puppeteer tools
  • 500+ contributors around the world manage the Playwright codebase
  • You can automate API tests as well

4. Can we automate Mobile Applications using Playwright?

Another major criterion while choosing the right automation tool for you is its capability to automate different types of applications. Especially the web and mobile applications combination is something that many are on the lookout for. Here is the overview of Playwright’s mobile application testing capabilities.

  • You cannot automate Native mobile apps
  • You can automate mobile web on Android emulators or real devices using ADB commands. However, it is still in the experimental stage
  • There is no official confirmation of iOS support yet

5. What reports can I get from Playwright?

Reporting is the next part we’ll be covering in our Playwright overview as it is a crucial aspect when deciding the right test automation tool for you. Here is the list of reporting options available in Playwright.

  • List Reporter – This is the default reporter of Playwright. It prints a line for each test being run
  • Line Reporter – It reports the last executed test and prints error details if there is a failure. Line reporter is useful to monitor the execution progress instead of viewing the entire test results.
  • Dot Reporter – It is a concise report that shows only a single character for each test execution.
  • HTML Reporter – It generates reports as a webpage
  • Blob Reporter – Use blob reporter when you run tests in parallel.
  • JSON Reporter – Generates report as JSON file
  • Junit Reporter -JUnit reporter produces a JUnit-style XML report.

6. Is Playwright open-source or commercial?

Playwright is an open-source tool.

7. Who is maintaining Playwright?

Microsoft released the first version of Playwright on Feb 1, 2020. As of writing this blog, 127 versions have been released and 500+ contributors around the world manage the Playwright codebase. That is a very good stat that can give you a lot of confidence in choosing Playwright.

8. Can I convert Cypress scripts to Playwright?

For those who have already used Cypress for your test automation and are in the thought of migrating, our Playwright overview blog also offers possible options to move to Playwright. There are multiple tools/plugins in the market to convert Cypress scripts to Playwright, and here’s the list.

  • cy2pw – This experimental node package has the capability to transform standard Cypress structures into Playwright.
  • cypress-to-playwright – It is a conversion tool that can parse the entire script directory of Cypress to Playwright structure. You can find the supported snippets by viewing the linked page.
  • ChatGPT – You can also try ChatGPT to convert your scripts.

9. Can I run Playwright from CI\CD tools?

Ensuring that your changes do not disrupt the production code is a vital requirement when it comes to test automation. The great news is that you can run your Playwright tests on a Continuous Integration tool for every commit and pull request. It even supports all major CI tools – Github Actions, Azure Pipelines, CircleCI, Jenkins, Bitbucket Pipelines, Gitlab CI, & Google Cloud Build.

Playwright Overview

One of the standout benefits of using Playwright is its speed. With parallel execution capabilities, multiple tests can run simultaneously on different browsers, saving valuable time in the testing process. This not only increases efficiency but also allows for more thorough testing coverage. Although we have discussed all the key factors a QA manager should consider in our Playwright overview blog, one must always see how well the tool will fit their testing needs and make the final call. We hope you are now in a better position to make that decision.

Playwright Reporting: Customizing the Dot Reporter

Playwright Reporting: Customizing the Dot Reporter

Playwright is a popular test automation tool that offers a lot of reporting options for its users such as built-in reporters, custom reporters, and support for integrating third-party reporters. The Playwright’s default in-built reporter is the list reporter. However, when running tests via the CI tool, Playwright will switch to the Dot reporter by default. There is also a good reason why the Dot Reporter is chosen as the default Playwright Reporting option during execution in Continuous Integration tools. We have even made a YouTube video explaining it and recommend you check it out.

Like any tool or feature, there will always be a few drawbacks. Based on our experience of working with Playwright while delivering automation testing services to our clients, we were able to overcome these drawbacks with a few workarounds. So in this blog, we will be sharing how you can customize the Dot reporter to address these drawbacks and enhance your Playwright reporting. But before that, let’s take a look at what the disadvantages are.

Disadvantages of Dot Reporter:

  • During the execution process, the Dot Reporter will not display the number of tests completed. So you’ll have to manually count if you want to get the total number of tests executed.
  • In the event of a failure, an ‘F’ will appear in red. But the issue is that it will not indicate which specific test has failed during execution.

Customization of Dot Reporter:

As stated earlier, Playwright reporting has built-in options and customizing capabilities as well. So, let’s delve into the customization aspect to address the disadvantages of Dot Reporter. If you prefer to watch the entire step-by-step tutorial as a video, you can check out our video covering the same. Or you can prefer to continue reading as well.

Step 1: Creating Reporter Listener Class

  • Create a folder by the name ‘utils’ inside your project directory.
  • Create a TypeScript file using the name ‘CustomReporter’ with the below code

import type {Reporter, FullConfig, Suite, TestCase, TestResult, FullResult} from '@playwright/test/reporter';
class CustomReporter implements Reporter {
 }
export default CustomReporter;

Step 2: Configure Reporter Listener in Playwright Config file

  • Open the playwright.config.ts file
  • Add the reporter listener file that you created in Step 1 in the Playwright config file

import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
 testDir: './tests',
 /* Run tests in files in parallel */
 fullyParallel: true,
 /* Fail the build on CI if you accidentally left test.only in the source code. */
 forbidOnly: !!process.env.CI,
 /* Retry on CI only */
 retries: process.env.CI ? 2 : 0,
 /* Opt out of parallel tests on CI. */
 workers: process.env.CI ? 1 : undefined,
 /* Reporter to use. See https://playwright.dev/docs/test-reporters */
 reporter: './utils/CustomReporter.ts',
 /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
 use: {
   /* Base URL to use in actions like `await page.goto('/')`. */
   // baseURL: 'http://127.0.0.1:3000',

   /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
   trace: 'on-first-retry',
 },

 /* Configure projects for major browsers */
 projects: [
   {
     name: 'chromium',
     use: { ...devices['Desktop Chrome'] },
   },
{
     name: 'firefox',
     use: { ...devices['Desktop Firefox'] },
   },
{
     name: 'webkit',
     use: { ...devices['Desktop Safari'] },
   },
 ],

});

Step 3: Declare & Initialize Properties

  • In the CustomReporter class, add three class properties
    • totalTests-To hold total tests in the test suite.
    • totalTestsExecuted-To count the number of tests that have been executed in the current execution.
    • noOfTestsPerLine-To count the number of test statuses or results to be shown in a line.
  • Initialize the properties in the constructor

class CustomReporter implements Reporter {
   totalTests: number;
   noOfTestsPerLine: number
   totalTestsExecuted: number

   constructor() {
      this.totalTests=0
      this.noOfTestsPerLine=0
      this.totalTestsExecuted=0
   }
}

Step 4: Add the onBegin method

  • Add the onBegin method.
  • Save the total tests to be executed in the totalTests variable.

class CustomReporter implements Reporter {
   totalTests: number;
   noOfTestsPerLine: number
   totalTestsExecuted: number

   constructor() {
       this.totalTests=0
       this.noOfTestsPerLine=0
       this.totalTestsExecuted=0
   }
 onBegin(config: FullConfig, suite: Suite) {
       this.totalTests = suite.allTests().length;
       console.log(`Executing ${this.totalTests} test(s)`);
   }
  
}

Step 5: Add the printTotalExecuted method

This method will be called to print how many tests have been executed against the total tests.


class CustomReporter implements Reporter {
   totalTests: number;
   noOfTestsPerLine: number
   totalTestsExecuted: number

   constructor() {
       this.totalTests=0
       this.noOfTestsPerLine=0
       this.totalTestsExecuted=0
   }

   onBegin(config: FullConfig, suite: Suite) {
       this.totalTests = suite.allTests().length;
       console.log(`Executing ${this.totalTests} test(s)`);
   }

   printTotalExecuted(){
       process.stdout.write(`[${this.totalTestsExecuted}/${this.totalTests}]\n`);
       this.noOfTestsPerLine=0
   }

}

Step 6: Add the onTestEnd method

After the execution of each test, the onTestEnd method will be invoked.


class CustomReporter implements Reporter {
   totalTests: number;
   noOfTestsPerLine: number
   totalTestsExecuted: number

   constructor() {
       this.totalTests=0
       this.noOfTestsPerLine=0
       this.totalTestsExecuted=0
   }
  
   onBegin(config: FullConfig, suite: Suite) {
       this.totalTests = suite.allTests().length;
       console.log(`Executing ${this.totalTests} test(s)`);
   }

   printTotalExecuted(){
       process.stdout.write(`[${this.totalTestsExecuted}/${this.totalTests}]\n`);
       this.noOfTestsPerLine=0
   }

   onTestEnd(test: TestCase, result: TestResult) {

   }

}

Step 7: Print the Total Tests Executed

  • Inside the onTestEnd method, check many tests are executed in a line.
  • If the count is equal to 50, then invoke the printTotalExecuted method to print the total tests executed so far and the total tests in the test suite.

onTestEnd(test: TestCase, result: TestResult) {
   if (this.noOfTestsPerLine==50){
       this.printTotalExecuted()
   }
}

Step 8: Increament totalTestsExecuted & noOfTestsPerLine variables

It is possible to print the skipped status in ANSI Yello color. You can also use different color codes based on your preference. You can check the available color codes here .


onTestEnd(test: TestCase, result: TestResult) {
   if (this.noOfTestsPerLine==50){
       this.printTotalExecuted()
   }

   ++this.totalTestsExecuted
   ++this.noOfTestsPerLine

   //Printing Skipped Status in ANSI yellow
   if (result.status === 'skipped') {
       process.stdout.write('\x1b[33m°\x1b[39m');
       return;
   }
}


Step 10: Printing Retry Status

  • If a test has Timed out or Failed and Playwright does know what status needs to be marked, then the test will be marked for Retry.
  • Since the test will be rerun, we need to decrease the totalTestsExecuted variable to ensure accuracy.

onTestEnd(test: TestCase, result: TestResult) {
   if (this.noOfTestsPerLine==50){
       this.printTotalExecuted()
   }

   ++this.totalTestsExecuted
   ++this.noOfTestsPerLine

   //Printing Skipped Status in ANSI yellow
   if (result.status === 'skipped') {
       process.stdout.write('\x1b[33m°\x1b[39m');
       return;
   }

   //Printing the test that marked for retry
   if (test.outcome() === 'unexpected' && result.retry < test.retries) {
       process.stdout.write(`\x1b[33mx\x1b[39m`);
       --this.totalTestsExecuted;
       return;
   }
}


Step 11: Printing Failure Status & Test Title

  • Concatenating test title with failure status.
  • After printing the status & title, call the printTotalExecuted method to print Total Tests Executed and Total Tests in the Test Suite.

onTestEnd(test: TestCase, result: TestResult) {
   if (this.noOfTestsPerLine==50){
       this.printTotalExecuted()
   }

   ++this.totalTestsExecuted
   ++this.noOfTestsPerLine

   //Printing Skipped Status in ANSI yellow
   if (result.status === 'skipped') {
       process.stdout.write('\x1b[33m°\x1b[39m');
       return;
   }

   //Printing the test that marked for retry
   if (test.outcome() === 'unexpected' && result.retry < test.retries) {
       process.stdout.write(`\x1b[33mx\x1b[39m`);
       --this.totalTestsExecuted;
       return;
   }

   //Printing failure status and test name
   if (test.outcome() === 'unexpected' && result.status === 'failed') {
       process.stdout.write('\x1b[31m'+"F("+test.title+")"+'\x1b[39m');
       this.printTotalExecuted()
       return;
   }

}


Step 12: Other Statuses (Flaky, TimedOut, & Passed)


onTestEnd(test: TestCase, result: TestResult) {
   if (this.noOfTestsPerLine==50){
       this.printTotalExecuted()
   }

   ++this.totalTestsExecuted
   ++this.noOfTestsPerLine

   //Printing Skipped Status in ANSI yellow
   if (result.status === 'skipped') {
       process.stdout.write('\x1b[33m°\x1b[39m');
       return;
   }

   //Printing the test that marked for retry
   if (test.outcome() === 'unexpected' && result.retry < test.retries) {
       process.stdout.write(`\x1b[33mx\x1b[39m`);
       --this.totalTestsExecuted;
       return;
   }

   //Printing failure status and test name
   if (test.outcome() === 'unexpected' && result.status === 'failed') {
       process.stdout.write('\x1b[31m'+"F("+test.title+")"+'\x1b[39m');
       this.printTotalExecuted()
       return;
   }

   if (test.outcome() === 'unexpected' && result.status === 'timedOut') {
       process.stdout.write('\x1b[31mT\x1b[39m');
       return;
   }

   if (test.outcome() === 'expected' && result.status === 'passed') {
       process.stdout.write('\x1b[32m.\x1b[39m');
       return;
   }

   if (test.outcome() === 'flaky') {
       process.stdout.write('\x1b[33m±\x1b[39m');
       return;
   }

}


Step 13: Finally, Add onEnd Method

  • Print total tests executed just in case it is missed before the end of the execution.
  • Print the status of the entire execution.

onEnd(result: FullResult) {
   if (this.noOfTestsPerLine !== 0) this.printTotalExecuted();
   console.log(`\nFinished the run: ${result.status}`);
}


Full Code:


import { FullConfig } from '@playwright/test';
import { FullResult, Reporter, Suite, TestCase, TestResult } from '@playwright/test/reporter';

class CustomReporter implements Reporter {
   totalTests: number;
   noOfTestsPerLine: number
   totalTestsExecuted: number

   constructor() {
       this.totalTests=0
       this.noOfTestsPerLine=0
       this.totalTestsExecuted=0
   }

   onBegin(config: FullConfig, suite: Suite) {
       this.totalTests = suite.allTests().length;
       console.log(`Executing ${this.totalTests} test(s)`);
   }

   printTotalExecuted(){
       process.stdout.write(`[${this.totalTestsExecuted}/${this.totalTests}]\n`);
       this.noOfTestsPerLine=0
   }

   onTestEnd(test: TestCase, result: TestResult) {
       if (this.noOfTestsPerLine==50){
           this.printTotalExecuted()
       }

       ++this.totalTestsExecuted
       ++this.noOfTestsPerLine

       //Printing Skipped Status in ANSI yellow
       if (result.status === 'skipped') {
           process.stdout.write('\x1b[33m°\x1b[39m');
           return;
       }

       //Printing the test that marked for retry
       if (test.outcome() === 'unexpected' && result.retry < test.retries) {
           process.stdout.write(`\x1b[33mx\x1b[39m`);
           --this.totalTestsExecuted;
           return;
       }

       //Printing failure status and test name
       if (test.outcome() === 'unexpected' && result.status === 'failed') {
           process.stdout.write('\x1b[31m'+"F("+test.title+")"+'\x1b[39m');
           this.printTotalExecuted()
           return;
       }

       if (test.outcome() === 'unexpected' && result.status === 'timedOut') {
           process.stdout.write('\x1b[31mT\x1b[39m');
           return;
       }

       if (test.outcome() === 'expected' && result.status === 'passed') {
           process.stdout.write('\x1b[32m.\x1b[39m');
           return;
       }

       if (test.outcome() === 'flaky') {
           process.stdout.write('\x1b[33m±\x1b[39m');
           return;
       }

   }

   onEnd(result: FullResult) {
       if (this.noOfTestsPerLine !== 0) this.printTotalExecuted();
       console.log(`\nFinished the run: ${result.status}`);
   }
}
export default CustomReporter;


Conclusion:

In this blog, we have shown how to overcome the Playwright reporting issues usually seen with the Dot Reporter. In addition, you can use the onEnd method to print a summary of the entire execution, including Total Passed, Total Failed, Total Skipped, and Total Flaky.

The customization of Playwright Dot Reporter is a valuable tool for developers and testers looking to enhance their automated testing processes. Through the use of custom reporters, users have the ability to tailor their test reports to fit their specific needs and preferences.

One of the main benefits of using custom reporters is the flexibility it offers. With Playwright Dot Reporter, users can choose which information they want to include in their reports and how they want it displayed. This allows for more targeted and organized reporting, making it easier to interpret test results and identify any issues that may arise.

TOSCA Automation Tool: What is It? Why Use It?

TOSCA Automation Tool: What is It? Why Use It?

Have you ever felt overwhelmed by complex deployment processes or felt it tedious to integrate multiple tools to get things done? Then TOSCA is a great tool that can solve all your problems. But what is the TOSCA Automation tool? How does it work? How exactly can it benefit you? These are all the major questions we will be answering in our blog. Being a leading automation testing company, we have expertise in a range of automation tools and TOSCA is one of them. So let’s get started!

What is the TOSCA Automation Tool?

TOSCA (Test Automation Software for Continuous Application) is a powerful tool developed by Tricentis and is revolutionizing how organizations manage and deploy their cloud applications. It has the capability to achieve end-to-end automation testing without having to write any code. It supports a graphical model-based approach that enables testers to create and maintain tests by defining the business processes and application workflows instead of scripting. The best part of the TOSCA Automation tool is that it supports a wide range of technologies such as web, mobile, desktop applications, APIs, and even databases.

At its inception, TOSCA was born out of a need for standardization and automation in cloud computing. But it has evolved ever since then to become the go-to choice for enterprises looking to streamline their IT operations and improve efficiency. The primary reason for this kind of popularity is that TOSCA has been able to keep pace with business needs by constantly introducing new features and capabilities.

Key Features of the TOSCA Automation Tool

TOSCA is designed to support a wide range of testing needs in modern software development environments. And to achieve that it offers a robust set of features that will enhance the efficiency, coverage, and ease of automated testing.

Graphical Modeling

The standout feature of TOSCA is its graphical modeling capabilities. This feature allows users to visually represent complex system architectures and their dependencies clearly and intuitively. As stated earlier, the TOSCA Automation tool is scriptless so you can easily drag and drop components onto a canvas. Though we utilize the Gherkin format while scripting in Selenium to ensure that all stakeholders can easily understand the purpose of each script, the visual representation makes it a lot easier to collaborate among team members and other department stakeholders too.

Automated Deployment

Another significant feature of TOSCA is its automated deployment and provisioning capabilities. It allows users to define their infrastructure requirements in a template in which they can specify how resources should be provisioned and configured. The users can then utilize this template to automate the deployment process and ensure consistency across different environments.

Additionally, organizations can even easily replicate their infrastructure setup across multiple instances without any manual work or intervention. This makes it a lot easier to roll out new applications or updates and also to minimize downtimes during times of failure. In addition to saving time, it even reduces the risk of human errors during deployment.

Integration Capabilities

One way TOSCA is able to achieve this kind of seamless deployment is due to its capability to integrate with a wide range of tools. Be it DevOps tools like Jenkins or Ansible, or cloud management platforms like AWS or Azure, TOSCA has the ability to offer a more holistic approach to automation and orchestration. This level of connectivity makes it easy to streamline the processes across different platforms and across diverse infrastructures. The wide range of support makes it possible to be used by different organizations that use different tech stacks that suit their needs.

Scalability & Flexibility

A by-product of these key features we’ve seen is that it makes the TOSCA automation tool highly scalable & flexible. Its scalability allows users to easily adjust resources such as server and storage requirements based on their needs. Whether you’re deploying a simple application or a complex network infrastructure, TOSCA has the required flexibility to customize your deployment process the way you want it. Any tool that can help organizations meet their changing business needs will definitely turn out to be a success. And TOSCA is no exception.

How does TOSCA work?

It’s great that the TOSCA automation tool offers such great features. But how does it actually get the job done? TOSCA actually breaks down complex applications into smaller and simpler components through graphical modeling. The application’s structure and dependencies are defined using templates that are written in a standardized modeling language. The template has nodes and each node represents elements such as servers, databases, and networking components. Relationships between these nodes are made with the help of properties to denote how they interact with each other. The scripts needed for deployment are stored as artifacts. The execution of a TOSCA template follows a structured sequence where the orchestrator reads and interprets the template instructions. Finally, it performs actions such as provisioning resources, configuring settings, and managing dependencies based on the defined relationships.

Conclusion

So it is evident that the TOSCA Automation Tool is equipped with a comprehensive set of features designed to address the challenges of modern software testing. Features such as graphical modeling, scriptless testing, automated deployment, and robust integration capabilities make it a popular choice. It has direct impacts such as enhancing test automation, improving test coverage, and accelerating time-to-market. We will definitely be going deep in terms of how to use TOSCA in your day-to-day projects in our upcoming blogs about it. So make sure to keep an eye out on our website.