Sunday, August 22, 2021

Playwright with Test Runners

Playwright with Jest and Playwright native Test Runner

Wanted to share this as I gave a try and experienced a bit with Playwright on both test runners which are Jest and also with Playwright's native test runner Playwright Test. I have jotted down a few points on both of these test runners with JavaScript.

Let's get started ..!!!


Few differences between Playwright-Jest Vs Playwright Test



Vs




Authentication to skip Login - Usually we use microsoft authentication and on this part both the test runners are pretty much the same. We can actually add cookies or save the storage state to skip the login for multiple tests in one shot. To do that first open the Playwright's Codegen.

On your terminal on VS code, run this command npx playwright codegen --save-storage=cookie.json and you will see two windows opening up one is Incognito browser and other is Playwright Inspector like below.


Type the command and hit enter. You will see something like below


Now type in your website name on this incognito browser opened for you to store the cookies with name 'cookie.json' in your project folder
I'm using the website Automation Practice for the demo purpose and just as an example. 

Basically you navigate through the website manually and on the right you see your playwright inspector adding code for you. You can use this code or you may not depending on your priority. I've just navigated manually on this website using Playwright’s codegen here and saved the necessary cookies for my login.

Once you are done on navigating through different options, you can close the playwright inspector and the incognito browser.



Once you close the two windows you will see automatically 'cookie.json' file is saved to your project folder on VS code.



This file is the required cookie file for you to use to skip the login for your tests. After this run the following command below

npx playwright open --load-storage=cookie.json http://automationpractice.com/index.php(Your Website name) 

on your VS Code Terminal



Now, run the command 

npx playwright codegen --load-storage=cookie.json http://automationpractice.com/index.php  

on your VS Code Terminal to see how playwright writes your test code for you to use as shown below. 




You run these last two --load-storage commands mentioned above to restore all your cookies and local storage for your web apps to authenticated state.

In my case I validated the last two commands but mostly I've used only 'cookie.json' generated from the very first command mentioned above here which is 

npx playwright codegen --save-storage=cookie.json


For reference Command Line tools


Now in your code you can add this like in two ways: -
For Authentication reference: Playwright-Authentication

With Playwright-Jest:
  • Add Cookies
                 const fs = require('fs')
               const { chromium } = require('playwright')

               let browser, context, page

                    browser = await chromium.launch( { headless : false} )
context = await browser.newContext({
viewport: {
width: 1920,
height: 1080,
},
})

const cookies = JSON.parse(fs.readFileSync('./cookie.json', 'utf8'))
await context.addCookies(cookies)
page = await context.newPage()
await page.goto('Your Url')

                                 ( OR )
  • Storage State : 
               let browser, context, page

                    browser = await chromium.launch()
page = await browser.newPage()
await page.goto('Your Url')
                  await page.context().storageState({ path'./cookie.json' });


With Playwright Test Runner: 

Playwright.config.(js or ts) file
projects: [
{
name: `Chrome`,
use: {
storageState: 'cookie.json',
browserName: `chromium`,
channel: `chrome`,
headless: false,
viewport: { width: 1720, height: 850 },
screenshot: `only-on-failure`,
video: `retain-on-failure`,
trace: `retain-on-failure`
}
},
I preferred the second one -----> "With Playwright Test Runner" First capture the cookies with playwright codegen command "npx playwright codegen --save-storage=cookie.json" and a new 'cookie.json' file is saved into your root directory with all the required cookies in it. Now, add this line storageState: 'cookie.json' like shown above in "playwright.config.js" or "playwright.config.ts" file and you are pretty much good to run your tests which will skip login.


Assertions We get a little more assertions with Playwright Test compared to Jest.


Retries -  Jest when using with jest-circus/runner and annotation with 'test' only not with 'it' the retries work for tests with Jest. In the test we can use like jest.retryTimes(1) for example to run the test one more time incase of failure. 

However, you have to do a global setup and teardown in jest and this jest retries did not show me any console message that it retried for 1 time.

Here, Playwright test runner is absolutely brilliant where it provides this retries inbuilt when using the Playwright Test. It retries the failed test and gives you console message as well like below.

In your playwright.config.js this is how it looks like:






Screenshot & Videos for failed tests - You can get screenshots of failed tests in both Playwright-Jest and Playwright Test. 

Screenshots are also pretty much easy with Playwright Test all you need is to just add a simple and single line of code in your config file. With Jest you have to do a set up by adding a long line of code using CustomEnvironment.js file.

Video of the tests are one of the options which jest did not have where in Playwright Test have this feature inbuilt defining in its playwright.config.js file.

Screenshot set up with Jest-Playwright:



Screenshot and Video set up with Playwright Test:





Element Screenshot - You have this feature of capturing a screenshot at element level only in Playwright Test and this feature is not available in Playwright-Jest.



Test Execution Time 
- Both Playwright-Jest and Playwright Test execute tests in parallel by default which is a fantastic feature when compared to any other tools like Cypress.The test execution time is almost the same in both but Playwright Test is a bit faster than Playwright-Jest with what I've experienced.



Reporter options on your console - With Playwright Test runner you have various reporting options to display your test results on the console like list, line, json, dot, junit which you don’t have with Playwright-Jest.
 


Test Reporting options - you have different options like Jest-stare, jest-html-reporter and Allure with Playwright-Jest. Playwright Test is launched recently in the month of June 2021 with playwright version 1.12 Playwright Test I think, and it's very new in the market. 

Playwright supports Allure reporting with npm package to install “experimental-allure-playwright“

We can get a test report something like this below:











































With Playwright Version 1.16 playwright team introduced their own new html reporting 
option with the command “npx playwright show-report” and you can see the screenshot, trace and video of the failed test attached to the html report as shown below. cool isn't :) !



Playwright team is doing a fantastic job already coming with various new features with playwright.

Playwright Test runner supports both Allure reporting and Playwright's own Html Reporting now as mentioned above.

Locator keywordWith Playwright version 1.14 we have the keyword 'locator' in place which is just replacement of '$' to 'locator' for example:

From

const element = page.$('selector')

To

const element = page.locator('selector')



API Testing  With Playwright version 1.16 we can do API testing just like supertest for example. Release link : playwright v1.16
Official documentationPlaywright API Testing


Conclusion:

In my case I felt both are brilliant and not much a difference but only some features like retries, video capture, console test result display, assertions with expect, tracing options are pushing me towards Playwright Test runner. 

Working with playwright test runner definitely blown away my mind with it's concept of Fixtures and Folio on TypeScript and other cool features.

Note: Folio is deprecated and archived by the owner now and replaced with Playwright test runner v1.12.0 Playwright test runner

Folio deprecated, GitHub repo: Folio

It is definitely faster when working with JavaScript as well, giving you options and features which are specific in meeting your requirements. There's much more for you to explore on it in the store.

For sample boiler plate code on GitHub:Playwright-JavaScript please click the link below
      •  Playwright test runner:  Playwright Test (Without using Page fixture in Tests)  
For sample boiler plate code on GitHub:Playwright-TypeScript please click the link below

 

Happy Automation Testing Guys !!! :)







Thursday, August 5, 2021

Playwright Vs Cypress

Playwright Vs Cypress For Frontend Test Automation

In this blog post I'm sharing some really cool key features of Playwright over Cypress. When working in our project on a Single Page Application (SPA) we were already using Cypress. 

We wanted to leverage our test automation in terms of Cross browser testing, Developing Test code and Parallelisation. 

Here are some of the key points listed below to consider Playwright over Cypress. 

I've used both Playwright with Jest and Playwright test runner in our project.


What is Playwright?

Playwright is a node library to automate chromium, firefox and webkit (safari) with a single API. It is built on top of Puppeteer. It is developed by the founders of Puppeteer from google initially and now maintained by Microsoft. Playwright support multiple language bindings like TypeScript, JavaScript, Java, Golang, C# and Python for now. It has good features like
  • Autowaits - Waits automatically for the elements in the DOM to be available.
  • Scenarios - Deals with multiple pages, tabs, pop-up's, Iframes
  • Intercept - Performs stubbing and handles network activity
  • Browser versions - runs tests on latest versions of browsers and no need to download browsers on your computer. npm i -D playwright will install the browsers with latest versions for you on Node.js and JavaScript/TypeScript Environment
  • Webkit - Runs your tests on the safari browser on Mac, Linux and Windows
  • Emulate - Mobile devices with geo locations and permissions
  • Inbuilt - Native Test runner called Playwright Test runner available now. It also supports Test recording, Video recording and Screenshot capture
  • Official Website - https://playwright.dev/docs/intro
  • Shadow DOM - Good support for handling shadow DOM selectors
  • Test Runners - Supports you to choose your own test runners like Jest, AVA and Mocha. Mostly, recommended to use Playwright's native test runner - "Playwright test"


Fixtures: Playwright Test is based on the concept of the test fixtures. Test fixtures are used to establish environment for each test, giving the test everything it needs and nothing else.

Playwright's own inbuilt fixtures are:-

  • Browser - Browser instance is shared between all tests in the same worker - this makes testing efficient. However, each test runs in an isolated BrowserContext and gets a fresh environment. 

All tests run in worker processes. These processes are OS processes, running independently, orchestrated by the test runner. All workers have identical environments and each starts its own browser.

You can't communicate between the workers. Playwright Test reuses a single worker as much as it can to make testing faster, so multiple test files are usually run in a single worker one after another. 

A worker is an object created using a constructor that runs a named JavaScript file and this file contains the code that will run in the worker thread.


  • Context - Isolated BrowserContext instance, created for each test. Since contexts are isolated between each other, every test gets a fresh environment, even when multiple tests run in a single Browser for maximum efficiency.

    BrowserContexts provide a way to operate multiple independent browser sessions.If a page opens another page, e.g. with a window.open call, the popup will belong to the parent page's browser context.

    Playwright allows creating "incognito" browser contexts with browser.newContext([options]) method. "Incognito" browser contexts don't write any browsing data to disk.


  • Page - Isolated Page instance, created for each test. Pages are isolated between tests due to fixtures.context isolation. Page provides methods to interact with a single tab in a Browser in Chromium for example. One Browser instance might have multiple Page instances.



What is Cypress?




Cypress is a frontend automation testing tool built for modern web applications.Test and mock API's for API automation testing.Cypress don't support this page object design pattern and they support App action pattern using the test data in the fixtures folder and re-usable code in the support folder in commands.js section of cypress.

Using cypress dashboards make cypress a paid tool to achieve parallelisation test run but videos, screenshots and retries of tests are well supported by cypress.Coming to cross browser testing cypress supports Electron, Chrome, Firefox and Microsoft edge browsers.


Differences between Playwright Vs Cypress

1Autowaits - When we write commands for example, we want to do a type and click operation for instance.

In Cypress :

Type:  Cypress.Commands.add('typeText', (selector, text) => {

cy.get(selector).click()

return cy.get(selector).type(text, { timeout: 1000 })

})


Click:  Cypress.Commands.add ('selectorClick', selector => {

return cy.get(selector).click({ force: true })

})


We get the element first and do the respective operation. 


In playwright we don’t really need to get the element and perform operation on it. Playwright automatically waits for the element to be available until the operation is performed.


In Playwright :

      Type:  async  waitAndFill(selector, text) {

await page.waitForSelector(selector)

return await page.fill(selector, text) 

}


    Click :            await page.click(selector)


These are called actionability checks in Playwright. It waits for the element to be attached to DOM, available and visible and then only it performs the type or click operation on the element. 


Fill is a Type operation in Playwright but with clearing the existing text and then types the text needed.Playwright's actionability check of element includes whether element is Visible, stable, attached to DOM and whether is it Enabled and after all these checks then only it performs the Type(Fill) or Click operation on an element for instance.


More or less almost same rule applies to actions like check, dblclick, tap, uncheck, hover, scrollintoViewIfNeeded, screenshot.




2Selectors 

When getting the selectors for Cypress if we want to check if an element is visible when writing test automation framework, it can be three or four functions we write for example below for the same function for 4 different types of locators 

             


           CSS or Classname:    Cypress.Commands.add('isVisible', selector => {

                                      return cy.get(selector).should('be.visible')

                                                })


              With XPATH:       Cypress.Commands.add('isXpathVisible', selector => {

                                                  return cy.xpath(selector).should('be.visible')

                                                })

              With data-cy:     Cypress.Commands.add('isdata-cyVisible', selector => {

                                                   return cy.get(`[data-cy="${selector}"]`).).should('be.visible')


                                                })


              With data-test-id :   Cypress.Commands.add('isdata-test-idVisible', selector => {

                                                   return cy.get(`[data-testid="${selector}"]`).).should('be.visible')


                                               })


When getting the selectors with Playwright it is more hassle free. Just one function to define like below when developing test automation framework for any selector.


you can find a specific element with it's selector of type id, data-cy, data-test-id, css, xpath and text and return Visible


async isElementVisible(selector) {

let isVisible = true

await page.waitForSelector(selector)

await page

.locator(selector, { visible: true, timeout: this.timeout })

.catch(() => {

isVisible = false

})

return isVisible

}




3. Custom Waits: Playwright has custom wait option for lazy loading of the page or certain network conditions are met. 

                  async waitForPageLoad() {

              const isPageLoaded = await page.waitForLoadState('domcontentloaded')

              return isPageLoaded

                }



4. Choice of Test Runner: With Cypress we are restricted to Mocha. With Playwright we can use our own choice of test runners like Jest, AVA, Mocha and Playwright’s own native Test runner available now. Most popular ones are playwright's inbuilt native test runner and Jest with playwright.



5Handling cookies and local storage:  With Cypress we use Json web tokens or OAuth usually but with Playwright it’s very simple and no need to use Json web tokens or OAuth instead we can save the cookies and storage state with playwright’s Codegen and playwright inspector. It’s very easy. Once the session stored, we can skip the login for multiple tests in one go.


6Clicking the element with Text: With Cypress we kind of click the element sometimes with it’s text with command like below

             For ex: cy.contains(text).click()


With Playwright it is click the element grabbed as a selector with text like below: -

Put all the locators in one locators.js file like below             

                          export const newButton = 'text=New'  


Selector In the Code,  

                           await page.click(newButton)  Selector is ‘text=New’



7Handling promises: With Cypress sometimes writing code is tedious when we have a bunch of nested chaining like then, then, then, etc… this is handled beautifully in Playwright with async/await feature resolving the promises having the perfect JavaScript/TypeScript flavour with the best way of coding tests. I call it Test Automation Engineer's Paradise :) 


8Running in Safari Browser: Cypress don’t have this feature but Playwright can run the safari browser with webkit on Mac, Linux and Windows without downloading the browsers on your computer.


9Headless mode: Cypress does not run in headless browser by default but Playwright runs headless on chrome, firefox, edge and safari browsers.


10Timeouts: Cypress re-try assertions to wait until the timeout as specified in cypress.json, Basically wait for the element to find until the timeout. Playwright waits for the UI-elements by default before running any operations. Usually, No explicit timeouts needed for Playwright.


11. Parallel Crossbrowser Testing: Playwright allows you to run tests on multiple browsers at same time. Cypress don’t.


12. Parallel Testing: Cypress allows you with parallel testing with Cypress Dashboards. You have to buy the Team plan, Business plan or Enterprise plan in order to achieve parallelisation and get it running on CI. With Playwright it is free by default with its native test runner or with Jest.


13. Faster Execution Locally with Headless Mode: Playwright test execution is much faster than Cypress locally as well with parallelisation by default.


Playwright with Jest Execution in Headless Mode (Locally):



Total Time for 41 tests: 14.419 seconds



Playwright Native Test Runner in Headless Mode (Locally):



Total Time for 41 tests:  
9 seconds



Cypress Headless run (Locally):



Total Time for 40 tests: 35.0 seconds



14. Faster Execution on CI: Playwright test execution is much faster than Cypress as it offers parallelisation by default. we use GitLab CI. Cypress is a bit slow at the start up with CI when installing npm packages in the very initial step. With playwright you can now execute the tests on headless mode with Safari, Firefox, Edge and Chrome. Yes you've read it right :) !


Playwright with Jest on GitLab CI parallel execution:

Playwright with Jest : Total Time for 41 tests in Parallel:  02 mins 05 seconds





Playwright Native Test Runner on GitLab CI parallel execution:

Playwright Test Runner : Total Time for 41 tests in Parallel:  01 min 35 seconds



Cypress on Gitlab CI (Parallel Execution with cypress dashboards):


Cypress : Total time for 40 tests: 3 mins and 05 seconds                                                                     




15. Test Reporting Options: With Playwright we can use jest-stare,  html-test-report, Allure reporting and playwright's own inbuilt test report. With Cypress, we have Allure or Mochawesome

reporting.



16. Folio and Fixtures from Playwright: Folio comes with only Playwright's inbuilt native test runner and makes your

tests run in parallel and handles the re-try of flaky failures.


Fixtures are a basic set up for our tests to runThere are two types of fixtures called Test fixtures and Worker fixtures.

For reference Please see https://github.com/microsoft/folio


Folio and Playwright-CLI is now deprecated and archived by the owner link below.

Folio Playwright-CLI


This is replaced now with Playwright test runner V1.12.0. Playwright Test Runner



17. Playwright Test runner is definitely a worth to try and blown away my mind when I tried myself. It's test execution is so fast and kind of similar to Jest in terms like assertions with expect, hooks. However, there is much more in the store to explore with it. You have everything needed for the test run defined in playwright.config.js or playwright.config.ts.



18. Docker Images: With Cypress we may use three different types of docker images when integrating with CI in yaml file. we use three kind of docker images depending on our requirement Cypress-docker-images it can be cypress/base, cypress/browsers (OR) cypress/included. With Playwright, It is just one Docker Image Playwright-Docker-Image can be mcr.microsoft.com/playwright:focal for instance.



19
. Drivers and Browsers Installation: With Selenium, you have to install drivers like geckodriver, chromedriver and browsers like firefox, chrome. With Cypress, you have to at-least install browsers on your PC. With Playwright, You don't have to install both.



20. Visual Regression Testing: With Cypress we have to use third party tool like percy.io to achieve the Visual regression testing. Playwright with Jest gives you the best option for Visual regression testing as Jest comes with wonderful feature of Image snapshot with npm package Jest-Image-Snapshot


All you need to do is to run the npm install command npm i --save-dev jest-image-snapshot.Visual Regression testing is very easy to setup and run tests with Playwright-Jest. 


With Playwright Test runner version starting from 1.12, we can also do now the visual comparisons with snapshots just like jest. Playwright visual testing: Playwright Visual Testing 




Conclusion: 

I prefer to go with Playwright over cypress on Web Test Automation for the following reasons:

  • Developing the asynchronous test code with async/await keywords
  • Save cookies and local storage easily with playwright's codegen to skip login
  • Ease of using selectors. Selector can be any like data-test-id, id, xpath, css, text. Playwright handles it as one locator into one function.
  • Supports IFrame and svg locators
  • Implement page object design pattern
  • Parallelisation is free by default compared to cypress where you have to buy a plan to use cypress dashboard
  • Faster test execution locally and on CI
  • Choice of choosing my own Test Runner 
  • Playwright supports working with multiple tabs or multiple pages. Cypress don’t
  • Playwright supports multiple language bindings like C#, Golang, Java, Python, JavaScript and Typescript. Cypress supports only JavaScript and TypeScript
  • Goodbye to drivers and browser installations
  • Runs headless on chrome, firefox, edge and safari browsers locally and on CI
  • Cross browser parallel testing including safari    


Happy Automation Testing Guys !!!  :)

 


Robot Framework - Frontend Test Automation Framework generated by AI

  Robot Framework with Browser Library Web Test Automation Framework Developed With The Help Of AI Search Agent. In this article, we will di...