Capture Browser network traffic or logs and events in Automation Testing using WebdriverIO

Problem: In real world scenarios there are lot of test scenarios where we need to capture the network traffic and have to analyse that. This is mainly used for Back-end testing where different request and response needs to be analysed. Performance Testing tools have inbuilt features to capture and analyse it. But in Automation Testing also we can do this using open source Automation Testing tool.

Tools: In this solution we are using WebdriverIO. WebdriverIO is an open source automation test framework developed in Javascript . It’s build on nothing but Selenium.

Process: Devtools and Intercept are services provided by WebdriverIO to capture the network traffic when the website gets loaded.

Devtools Service

Installation: npm install @wdio/devtools-service — save-dev. This will install the service locally in the project as node package inside package.json.

Configuration: Devtools service need to be mentioned wdio.conf.js file. This is WebdriverIO configuration file.

Code: Following is a sample Javascript test code which will print in console the network traffics available at the time when website (https://www.google.com) gets loaded.

describe('Validating Network logs',()=>{
it('Capturing network logs',()=>{
browser.cdp('Network', 'enable')
browser.on('Network.responseReceived', (params) => {
console.log(params.response.url);
})
browser.url('https://www.google.com');
})
})

Intercept Service

Also to capture the events generated in network tab of the browser due to actions made on website we can use WendriverIO Intercept Service.

Installation: npm install wdio-intercept-service -D
This will install the intercept service. Next we need to add it under services section.

Code: Following is a sample code to use intercept service.

describe('capture events', () => {it('capture the events from browser', () => {browser.url('https://webdriver.io');browser.setupInterceptor(); // This will start the intercept service
and will capture the events for the
actions performed in website

$("//button[@onclick='throwInlineError()']").click();
$("//button[@onclick='throwReferenceError()']").click();
var request = browser.getRequests(); // All the events will get
stored in a list format

console.log(request[0].body); // This will print the body of the
first event captured
})})

For more reference go to https://webdriver.io/docs/devtools-service.html

Software Development Engineer in Test | DevOps Engineer | Python Developer