Introduction
If you need to log into a website, perform custom actions, or run arbitrary JavaScript during a test, the best approach is to use Test Scripts. Test scripts are powerful tools that allow you to extend and control the behavior of your automated tests by injecting custom code into the testing process. Whether you need to interact with authentication processes, manipulate data, simulate user interactions, or run specific JavaScript functions, test scripts provide the flexibility to do so.
By embedding test scripts within your testing workflow, you can simulate a wide range of real-world scenarios, from logging into a site with specific credentials to executing dynamic actions on the page, making your automated tests more robust and reflective of user behavior. Test scripts can run before, during, or after specific steps in your test, giving you full control over the execution flow and enabling you to test complex scenarios that would otherwise be difficult or impossible to automate.
A script lets you automate a test. The following is a basic example of logging into a site before running a test on a specific page:
// EXAMPLE: log into a site before measuring a page
// Disable logging: we don’t want the login page to appear in test results
logData 0
// Visit the login page, enter the username and the password into the fields, and press “Submit”
navigate https://my-site.com/login
setValue name=email darth@vader.com
setValue name=password foooooooooooooooorce
click innerText=Sign in
// Now, as we’ve signed in, enable logging again
logData 1
// And go the page we’re measuring
navigate https://my-site.com/dashboard
Here is another example where we open a chat support window:
// EXAMPLE: measure what happens when we interact with the page
// Go the page we’re measuring
navigate https://my-site.com/dashboard
// Give it a bit of time to initialize after loading
sleep 5
// Open the support dialog and wait for the page to become idle
execAndWait document.querySelector('.chat-dialog > button').click()
Please note that Lighthouse metrics are not affected by scripting except for setHeader and setCookie.
Updated 3 months ago