Use Custom JavaScript Assertions In Browser Tests Overview This guide describes how you can test a user interface (UI) using custom JavaScript in a browser test . JavaScript assertions support synchronous and asynchronous code.
To create an assertion using custom JavaScript:
Click Assertion and select Test custom JavaScript assertion . Write the body of your assertion. Optionally, select a target element in the UI. Click Apply . For more information about assertions, see Browser Test Steps .
Assert that an element is not on the page To verify that an element with a specific ID is not on the page, use return !document.getElementById("<ELEMENT_ID>");
.
To verify that elements are not on the page and return the number of elements in the console error, add the following in the body assertion:
Copy
var element = document . querySelectorAll ( "<SELECTORS>" );
if ( element . length > 0 ){
console . error ( element . length + " " + "elements exist" );
}
return element . length === 0 ;
Your browser test results contain console.error
logs.
To verify that a radio button is checked, use return document.querySelector("<SELECTORS>").checked === true;
in the body assertion.
Set the value of a specified local storage item To set the value of a specified local storage item, add the following in the body assertion:
Copy
localStorage . setItem ( keyName , keyValue );
return true
For example, to set the number of milliseconds elapsed since January 1, 1970, 00:00:00 UTC to “mytime”:
Copy
localStorage . setItem ( "mytime" , Date . now ());
return true
Assert on text contained in a rendered PDF You can use an external library to test the content of a rendered PDF.
To load external libraries, use a promise in the body assertion:
Copy
const script = document . createElement ( 'script' );
script . type = 'text/javascript' ;
//load external library
script . src = "https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.11.338/pdf.min.js" ;
const promise = new Promise (( r ) => script . onload = r )
document . head . appendChild ( script )
await promise
var loadingTask = pdfjsLib . getDocument ( "<PDF_URL>" );
return await loadingTask . promise . then ( function ( pdf ) {
return pdf . getPage ( 1 ). then ( function ( page ) {
return page . getTextContent (). then ( function ( content ) {
return content . items [ 0 ]. str . includes ( "<CONTENT_STRING>" )
})
})
});
Further reading Additional helpful documentation, links, and articles: