How to Run Playwright Tests With JavaScript on TestMu AI
Run your Playwright tests on the TestMu AI cloud grid to reach 50+ real desktop browsers and operating systems without maintaining local infrastructure. The connection is identical whichever framework you use: connect Playwright over a CDP WebSocket and pass a capabilities object, then pick your framework below.
Prerequisites
Before running any framework below, you need a TestMu AI account, your credentials, Node.js and npm, and the Playwright sample repository.
- A TestMu AI Username and Access Key. Get them from your TestMu AI Profile section. Don't have an account? Sign up for free.
- Node.js and npm installed.
- Clone the sample repository. Each framework option lives in its own subdirectory:
git clone https://github.com/LambdaTest/playwright-sample.git
cd playwright-sample
You can find your Username and Access Key on the TestMu AI Automation Dashboard by clicking the Access Key button at the top-right.
Set Your Credentials
Every framework authenticates the same way: your Username and Access Key are read from environment variables. Set them once. Pick your operating system:
- macOS / Linux
- Windows (CMD)
export LT_USERNAME="undefined"
export LT_ACCESS_KEY="undefined"
set LT_USERNAME=undefined
set LT_ACCESS_KEY=undefined
How the Sample Test Works
Every framework below builds a capabilities object (browser, version, platform, and your LT:Options) and connects Playwright to the grid at wss://cdp.lambdatest.com/playwright:
wsEndpoint: `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}`
What changes between them is only the setup file that holds this connection: a Playwright test fixture, a runner config, or a Cucumber.js world. That is what each tab covers.
Use the Capabilities Generator to build a capabilities block for any supported browser, version, and OS combination.
Run a Test with Playwright Using JavaScript
By default this page uses Playwright's own test runner (@playwright/test). Move into the matching subdirectory of the cloned repo, edit the setup file that holds the grid connection, install dependencies, then run. Prefer Jest or Cucumber.js? See Run a Test with Jest or Cucumber.js.
The JavaScript path connects to the grid through a Playwright Test fixture in lambdatest-setup.js, which patches the capabilities per project and reports test status.
- Go to the sample directory and install dependencies:
cd playwright-test-js
npm install
- The grid connection lives in
lambdatest-setup.js, a Playwright test fixture that patches the capabilities per project and reports test status:
/**
* Add the file in your test suite to run tests on LambdaTest.
* Import `test` object from this file in the tests.
*/
const base = require('@playwright/test')
const path = require('path')
const { chromium } = require('playwright')
const cp = require('child_process');
const playwrightClientVersion = cp.execSync('npx playwright --version').toString().trim().split(' ')[1];
// LambdaTest capabilities
const capabilities = {
'browserName': 'Chrome', // Browsers allowed: `Chrome`, `MicrosoftEdge`, `pw-chromium`, `pw-firefox` and `pw-webkit`
'browserVersion': 'latest',
'LT:Options': {
'platform': 'Windows 10',
'build': 'Playwright Build',
'name': 'Playwright Test',
'user': process.env.LT_USERNAME,
'accessKey': process.env.LT_ACCESS_KEY,
'network': true,
'video': true,
'console': true,
'tunnel': false, // Add tunnel configuration if testing locally hosted webpage
'tunnelName': '', // Optional
'geoLocation': '', // country code can be fetched from https://www.lambdatest.com/capabilities-generator/
'playwrightClientVersion': playwrightClientVersion
}
}
// Patching the capabilities dynamically according to the project name.
const modifyCapabilities = (configName, testName) => {
let config = configName.split('@lambdatest')[0]
let [browserName, browserVersion, platform] = config.split(':')
capabilities.browserName = browserName ? browserName : capabilities.browserName
capabilities.browserVersion = browserVersion ? browserVersion : capabilities.browserVersion
capabilities['LT:Options']['platform'] = platform ? platform : capabilities['LT:Options']['platform']
capabilities['LT:Options']['name'] = testName
}
const getErrorMessage = (obj, keys) => keys.reduce((obj, key) => (typeof obj == 'object' ? obj[key] : undefined), obj)
exports.test = base.test.extend({
page: async ({ page, playwright }, use, testInfo) => {
// Configure LambdaTest platform for cross-browser testing
let fileName = testInfo.file.split(path.sep).pop()
if (testInfo.project.name.match(/lambdatest/)) {
modifyCapabilities(testInfo.project.name, `${testInfo.title} - ${fileName}`)
const browser = await chromium.connect({
wsEndpoint: `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}`
})
const ltPage = await browser.newPage(testInfo.project.use)
await use(ltPage)
const testStatus = {
action: 'setTestStatus',
arguments: {
status: testInfo.status,
remark: getErrorMessage(testInfo, ['error', 'message'])
}
}
await ltPage.evaluate(() => {},
`lambdatest_action: ${JSON.stringify(testStatus)}`)
await ltPage.close()
await browser.close()
} else {
// Run tests in local in case of local config provided
await use(page)
}
}
})
- Run the test:
npm run test
Run a Test with Jest or Cucumber.js
Prefer Jest or Cucumber.js as your test runner? Pick your framework below.
Verified- Jest
- Cucumber.js
Jest connects through jest-playwright.config.js, which defines a connectOptions endpoint per browser (Chromium, Firefox, WebKit), each with its own capabilities.
- Go to the sample directory and install dependencies:
cd playwright-jest-js
npm install
- Open
jest-playwright.config.jsin theplaywright-jest-jsdirectory and provide your TestMu AI Username and Access Key. Each browser gets its own capabilities andwsEndpoint:
const cp = require('child_process');
const playwrightClientVersion = cp.execSync('npx playwright --version').toString().trim().split(' ')[1];
const caps_chromium = {
'browserName': 'pw-chromium', // Browsers allowed: `Chrome`, `MicrosoftEdge`, `pw-chromium`, `pw-firefox` and `pw-webkit`
'browserVersion': 'latest',
'LT:Options': {
'platform': 'Windows 10',
'build': 'Playwright-Jest Build',
'name': 'Playwright-Jest Test on Chromium',
'user': process.env.LT_USERNAME,
'accessKey': process.env.LT_ACCESS_KEY,
'network': true,
'video': true,
'console': true,
'tunnel': false, // Add tunnel configuration if testing locally hosted webpage
'tunnelName': '', // Optional
'geoLocation': '', // country code can be fetched from https://www.lambdatest.com/capabilities-generator/
'playwrightClientVersion': playwrightClientVersion
}
};
const caps_firefox = {
'browserName': 'pw-firefox', // Browsers allowed: `Chrome`, `MicrosoftEdge`, `pw-chromium`, `pw-firefox` and `pw-webkit`
'browserVersion': 'latest',
'LT:Options': {
'platform': 'Windows 10',
'build': 'Playwright-Jest Build ',
'name': 'Playwright-Jest Test on Firefox',
'user': process.env.LT_USERNAME,
'accessKey': process.env.LT_ACCESS_KEY,
'network': true,
'video': true,
'console': true,
'tunnel': false, // Add tunnel configuration if testing locally hosted webpage
'tunnelName': '', // Optional
'geoLocation': '', // country code can be fetched from https://www.lambdatest.com/capabilities-generator/
}
};
const caps_webkit = {
'browserName': 'pw-webkit', // Browsers allowed: `Chrome`, `MicrosoftEdge`, `pw-chromium`, `pw-firefox` and `pw-webkit`
'browserVersion': 'latest',
'LT:Options': {
'platform': 'Windows 10',
'build': 'Playwright-Jest Build',
'name': 'Playwright-Jest Test on WebKit',
'user': process.env.LT_USERNAME,
'accessKey': process.env.LT_ACCESS_KEY,
'network': true,
'video': true,
'console': true,
'tunnel': false, // Add tunnel configuration if testing locally hosted webpage
'tunnelName': '', // Optional
'geoLocation': '', // country code can be fetched from https://www.lambdatest.com/capabilities-generator/
}
};
module.exports = {
connectOptions: {
chromium: {
wsEndpoint: `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(caps_chromium))}`
},
firefox: {
wsEndpoint: `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(caps_firefox))}`
},
webkit: {
wsEndpoint: `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(caps_webkit))}`
}
},
browsers: ['chromium', 'firefox', 'webkit'],
}
- Run the test:
npm run test
Cucumber.js runs BDD scenarios written in Gherkin. The grid connection lives in a setup.js file, where a Cucumber Before hook builds the capabilities object and connects Playwright to the grid.
- Move into the Cucumber.js sample directory inside the cloned repo and install dependencies:
cd playwright-cucumber-js
npm install
- In your
setup.jsfile, specify your TestMu AI Username and Access Key, then add thebrowserName,browserVersion, andplatform:
const { setWorldConstructor, World, Before, After} = require("@cucumber/cucumber");
const { chromium } = require('playwright')
class CustomWorld extends World{
async setTestStatus(status, remark) {
await page.evaluate(_ => {}, `lambdatest_action: ${JSON.stringify({ action: 'setTestStatus', arguments: { status, remark } })}`)
}
}
Before(async (scenario) => {
const capabilities = {
'browserName': 'Chrome', // Browsers allowed: `Chrome`, `MicrosoftEdge`, `pw-chromium`, `pw-firefox` and `pw-webkit`
'browserVersion': 'latest',
'LT:Options': {
'platform': 'Windows 10',
'build': 'Playwright Sample Build with Cucumber Runner',
'name': scenario.pickle.name,
'user': process.env.LT_USERNAME,
'accessKey': process.env.LT_ACCESS_KEY,
'network': true,
'video': true,
'console': true,
'tunnel': false, // Add tunnel configuration if testing locally hosted webpage
'tunnelName': '' // Optional
}
}
// Create page and browser globals to be used in the scenarios
global.browser = await chromium.connect({
wsEndpoint: `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}`
})
const context = await global.browser.newContext();
global.page = await context.newPage();
})
After(async () => {
await global.browser.close()
})
setWorldConstructor(CustomWorld);
- Run the test:
npm run test
Visit the TestMu AI Automation Dashboard to view the results of your executed test with the Cucumber.js test runner.
Migrating an Existing Cucumber.js Suite to TestMu AI
If you already have a Cucumber.js suite running locally, wire it to the grid with these steps.
- In your
setup.jsfile, addBeforeandAftercode blocks for setting up and closing the remote browsers:
Before(async (scenario) => {
const capabilities = {
'browserName': 'Chrome', // Browsers allowed: `Chrome`, `MicrosoftEdge`, `pw-chromium`, `pw-firefox` and `pw-webkit`
'browserVersion': 'latest',
'LT:Options': {
'platform': 'Windows 10',
'build': 'Playwright Sample Build with Cucumber Runner',
'name': scenario.pickle.name,
'user': process.env.LT_USERNAME,
'accessKey': process.env.LT_ACCESS_KEY,
'network': true,
'video': true,
'console': true,
'tunnel': false, // Add tunnel configuration if testing locally hosted webpage
'tunnelName': '' // Optional
}
}
// Create page and browser globals to be used in the scenarios
global.browser = await chromium.connect({
wsEndpoint: `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}`
})
const context = await global.browser.newContext();
global.page = await context.newPage();
})
After(async () => {
await global.browser.close()
})
setWorldConstructor(CustomWorld);
- In the
CustomWorldclass, create asetTestStatusfunction that marks your test passed or failed on the TestMu AI platform:
class CustomWorld extends World{
async setTestStatus(status, remark) {
await page.evaluate(_ => {}, `lambdatest_action: ${JSON.stringify({ action: 'setTestStatus', arguments: { status, remark } })}`)
}
}
- After any assertions in your script, mark the test status as passed as shown below:
try {
assert.equal(title,
"How to use HyperExecute for scalable and reliable web automation testing | TestMu AI",
"Page title does not match");
await this.setTestStatus("passed", "Title matched");
} catch (e) {
await this.setTestStatus("failed", e);
throw(e);
}
- Run your test.
View Your Results
Go to the TestMu AI Web Automation Dashboard to see your Playwright test results, including video, network logs, and command-by-command execution.
Related Playwright Guides
Continue with these related guides:
