Automated UI/UX Testing with Puppeteer Mocha and Chai

Tariqul Islam
7 min readOct 19, 2018

--

Regression Testing is painful for tester for doing the test without any reasons again and again. So Tester can Automated the test by using the automated testing tools like puppeteer with mocha and chai. which will make testing interesting for tester and test can get red of boring task also. It can save the time and tester can concentrate on other task also.

Puppeteer for Testing

Puppeteer is a Node Js Library which provide high-level API to control Chrome or Chromium over the Development Tools Protocol of chrome browser. Puppeteer provide the headless browser functionality by default. We can also configured the Puppeteer to run non-headless Chrome or Chromium.

Most things that you can do manually in the browser can be done using Puppeteer! Here are a few examples to get you started:

Importance of headless browser for automated the testing

A headless browser is a web browser without a graphical user interface.

Headless browsers provide automated control of a web page in an environment similar to popular web browsers, but are executed via a command-line interface or using network communication. They are particularly useful for testing web pages as they are able to render and understand HTML the same way a browser would.

Mocha and Chai

Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun.

Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.

Testing Framework and assertion

Testing frameworks are used to organize and execute tests.

Assertion libraries are tools to verify that things are correct.
This makes it a lot easier to test your code, so you don’t have to do thousands of if statements.

Configure the Automated Testing Environment

Prequesites for automated testing

1. Node JS (v.1.8.10)
2. Puppeteer JS
3. Mocha
4. Chai ( Test Assertion Library )
5. node-cmd ( Run Command Line Command in Node JS)
6. opn (open the report of testing automatically to browser)
7. Express JS (Web server to serve report)
8. Mochawesome (for Report generation )

If your computer has Node js already check the version number by command

> node -v

Create the Directory from cmd or terminal for create the test project

> mkdir mocha-testing-puppeteer

Then go to that directory

> cd mocha-testing-puppeteer

Initial the Node Project by using this command below:

> npm init --yes

After that we have to install few npm package for that

> npm install --save mocha chai puppeteer

Create directory to mocha-testing-puppeteer directory named test , the Project structure will be

|-- mocha-testing-puppeteer
|---- test (Directory for where the test file are contain)
|---- package.json
|---- node_modules

In Test file we have to create configuration file will control the automated testing environment and chrome browser with puppeteer.

Changing some script in package.json file:

Create the Boostrap configuration file which will operate Chrome browser with Puppeteer for testing. Bootstrap file will be created at test/bootstrap.js location.

Figure 1.1 configure the Puppeteer for testing purpose

In Figure 1.1, line 2 to 4, I have import all the library for which is need for configure the puppeteer for automated testing.

In Line 7, I am using lodash library pick function make browser and expect variable, which i using it as global, those variable will be available within this project.

In Line 10 to 15, I have declared the opt object which contains the option attribute of the puppeteer those attirbute are works like:

  1. headless: Turn off or no headless mode, sometimes it’s useful to see what the browser is displaying. Instead of launching in headless mode, launch a full version of the browser using headless: false
  2. slowMo: the slowMo option slow down Puppeteer operations by the specified amount of milisecods.
  3. timeout: the timeout options will handle the puppeteer will stop operation after that time durations. I will make it to 0, so the puppeteer do not stop until the test is complete.
  4. args: which will takes other brower options which is control the browser beheaver. --start-maximized will open the browser with maximized mode and --window-size will open the borwser with resolutions.
before (async () => {  
global.expect = expect;
global.browser = await puppeteer.launch(opts);
});

From line 18 to 20, I have use mocah library funciton before which will do the task or operation which call in this function before start testing. expect is function for chai essertion library function.

global.browser = await puppeteer.lanuch(opts) it will run the Chromium or Chrome Browser with options which is defined in this code.

after ( () => {  
browser.close();
global.browser = globalVariables.browser;
global.expect = globalVariables.expect;
});

From 24 to 27, after is mocha library function, which will run after complete testing by mocha. browser.close() close the browser which is automatically run by puppeteer and then again call the browser and expect as global varible.

Then we will create the file in test folder named sample.spec.js file to project.

For Simple Testing Purpose we need to learn about some basic assertion of Mocha and Chai those are

  1. describe
  2. after and before
  3. it

describe()

Describe is just used for the sake of understanding the purpose of the tests , it is also used to logically group the tests . Lets say you are testing login functionality, so all types of login functionality tests could come under the outer describe function. Lets say describe('simple function for test', async () => {}) , I use async...await javascript functionality for stable testing durations.

it()

The it call identifies each individual tests but by itself. it does not tell Mocha anything about how your test suite is structured.

before() and after()

before is a hook. this function is call before the test is start within scope. And after is call after the test is done within describe scope also.

Figure 1.2, Sample Testing Files with Puppeteer

In Figure 1.2, i have added the testing block which will automatically start the test for login functionality for linkedin .

in line 3, I have added describe function named simple test for Linkedin Login functionality

describe('simple test for Linkedin Login functionality', async () =>{ })

In line 6 to 10,

In line 6 to 10, I have added before hook for run the code before start testing with mocha

before(async () => {
page = await browser.newPage();
await page.goto(“https://www.linkedin.com/");
await page.setViewport( { width: 1920, height: 1040} );
});

for page = await browser.newPage() is a puppeteer function will open the new page in chrome browser.

Then await page.goto('https://www.linkedin.com) will automatically browse to that Linkedin account.

After that await page.setViewport({ width: 1920, height: 1040}) this function set the view port of the browser page. change the resolution during testing time.

after(async function () {
await page.close();
});

await page.close()this function will close the page after the mocha complete the test.

it(‘should login to home page’, async () => {})

From line 24 , I have create the test case using it() function named login functionality is okay for linekdin account

const emailInput = “#login-email”;
const passwordInput = “#login-password”;
const submitSelector = “#login-submit”;

From line 25 to 27, I just add the selector of the Dom element of `Linkedin` login page.

Then find the selector of using `puppeteer` from line 29 to 31. Just use this function page.$(DOM_SELECTOR).

linkEmail = await page.$(emailInput);
linkPassword = await page.$(passwordInput);
linkSubmit = await page.$(submitSelector);

Then From line 33 to 34 I have clicked to `Email Selector` by this function named await DOM_SELECTOR.click({clickCount:3})of the linkedin page

await linkEmail.click({ clickCount: 3 });

Add by type function we can add value by with this statement await INPUT_DOM_SELECTOR.type(INPUT_ELEMENT_VALUE)

await linkEmail.type(‘sample email value’); // add the email address for linkedin //

And wait after execute click to that page by await page.waitFor(TIME_DURATION)

await page.waitFor(3000);

Create The Generated Test Case Report for Mocha

To generate the report for mocha testing we are using mochawesome npm package for that, it will generate the report automatically. And Install the open npm package to open the testing report to browser for see the testing report.

Install the package for mochawesome and opn

> npm install --save mochawesome opn express node-cmd

Then change the test command in package.json file:

mocha --timeout 0 ./test/bootstrap.js --recursive test --reporter mochawesome it will test all the test case and generate the reporting folder named mochawesome-report in root of project directory which contains the structure

.....
|-- mochawesome-report
|--- assets
|--- mochawsome.html
|--- mochawsome.json
.....

mochawesome.html is html type reporting for mocha testing.

Run The Generated To Express JS(Web Server) for Presentation Purpose

Create File name server.js at root of the project directory

Figure 1.3 Create the server to show generated report for mochawesome

Add the opn and node-cmd library for to boostrap.js file, for showing the generated report to borwser:

const opn = require('opn')
const cmd = require('node-cmd')

Then Modify the code in afterhook atboostrap.js file:

after(async () => {
....
setTimeout( () => { cmd.run('node server.js');}, 5000); setTimeout(() => {opn('http://localhost:9988');}, 2000);
....
})

Then we can open the terminal and run npm test it will run all the test and report will shows into default browser .

You find all the code in github following this link

--

--

Tariqul Islam
Tariqul Islam

Written by Tariqul Islam

Tariqul Islam have 10+ years of software development experience. He knows Python, Java, C#,PHP and other Computer languages.

Responses (5)