For certain k6 tests, we may want to vary the action taken based on content presented on the target test page. In order to accomplish this, we can use HTML elements to drive conditional logic within a k6 test plan. In this brief post, we will show you how to use k6 to dynamically evaluate HTML elements on a target test page.
Importing Required Modules
To read content from the page, we will need to import the parseHTML()
function from the built-in k6/html
module:
import { parseHTML } from 'k6/html';
Parsing HTML Elements
In order for us to obtain the HTML content from the target test page we will use the parseHTML()
function to evaluate the response body:
const response = http.get('https://k6.io'); const document = parseHTML(response.body);
Using the find()
method, we can select the page title element from the parsed HTML content:
const title = parseHTML(document).find('head title').text();
At this point, the variable “title
” contains the title of the target test page. We can use further conditional logic to evaluate next steps for our test based on the title content.
Did you know that RedLine13 offers a full featured, time limited free trial? Sign up now, and start testing today!