Get your setup working faster. Join our Discord for optimisation tips from elite testers.Join our Discord
Capabilities
Using Playwright with BrowserStack requires passing the custom capabilities in an object, and passing this object to the Playwright URL endpoint on BrowserStack. This section includes a sample script file along with a detailed reference of all the supported capabilities.
// fixtures.jsconstbase=require('@playwright/test');constcp=require('child_process');constclientPlaywrightVersion=cp.execSync('npx playwright --version').toString().trim().split('')[1];constBrowserStackLocal=require('browserstack-local');// BrowserStack Specific Capabilities.constcaps={os:'osx',os_version:'catalina',browser:'chrome',browser_version:'latest','browserstack.username':process.env.BROWSERSTACK_USERNAME||'YOUR_USERNAME','browserstack.accessKey':process.env.BROWSERSTACK_ACCESS_KEY||'YOUR_ACCESS_KEY','browserstack.geoLocation':'FR',project:'My First Project',build:'playwright-build-1',name:'My first playwright test',buildTag:'reg',resolution:'1280x1024','browserstack.local':'true','browserstack.localIdentifier':'local_connection_name','browserstack.playwrightVersion':'1.latest','client.playwrightVersion':'1.latest','browserstack.debug':'true',// enabling visual logs'browserstack.console':'info'// Enabling Console logs for the test'browserstack.networkLogs':'true'// Enabling network logs for the test'browserstack.interactiveDebugging':'true',}exports.bsLocal=newBrowserStackLocal.Local();// replace YOUR_ACCESS_KEY with your key. You can also set an environment variable - "BROWSERSTACK_ACCESS_KEY".exports.BS_LOCAL_ARGS={key:process.env.BROWSERSTACK_ACCESS_KEY||'YOUR_ACCESS_KEY',};// Patching the capabilities dynamically according to the project name.constpatchCaps=(name,title)=>{letcombination=name.split(/@browserstack/)[0];let[browserCaps,osCaps]=combination.split(/:/);let[browser,browser_version]=browerCaps.split(/@/);letosCapsSplit=osCaps.split(/ /);letos=osCapsSplit.shift();letos_version=osCapsSplit.join('');caps.browser=browser?browser:'chrome';caps.browser_version=browser_version?browser_version:'latest';caps.os=os?os:'osx';caps.os_version=os_version?os_version:'catalina';caps.name=title;};constisHash=(entity)=>Boolean(entity&&typeof(entity)==="object"&&!Array.isArray(entity));constnestedKeyValue=(hash,keys)=>keys.reduce((hash,key)=>(isHash(hash)?hash[key]:undefined),hash);constisUndefined=val=>(val===undefined||val===null||val==='');constevaluateSessionStatus=(status)=>{if(!isUndefined(status)){status=status.toLowerCase();}if(status==="passed"){return"passed";}elseif(status==="failed"||status==="timedout"){return"failed";}else{return"";}}exports.test=base.test.extend({page:async({page,playwright},use,testInfo)=>{// Use BrowserStack Launched Browser according to capabilities for cross-browser testing.if(testInfo.project.name.match(/browserstack/)){patchCaps(testInfo.project.name,`${testInfo.file} - ${testInfo.title}`);constvBrowser=awaitplaywright.chromium.connect({wsEndpoint:`wss://cdp.browserstack.com/playwright?caps=`+`${encodeURIComponent(JSON.stringify(caps))}`,});constvContext=awaitvBrowser.newContext(testInfo.project.use);constvPage=awaitvContext.newPage();awaituse(vPage);consttestResult={action:'setSessionStatus',arguments:{status:evaluateSessionStatus(testInfo.status),reason:nestedKeyValue(testInfo,['error','message'])},};awaitvPage.evaluate(()=>{},`browserstack_executor: ${JSON.stringify(testResult)}`);awaitvPage.close();awaitvBrowser.close();}else{use(page);}},});
// single_test.jsconstexpect=require('chai').expectconst{chromium}=require('playwright');constcp=require('child_process');constclientPlaywrightVersion=cp.execSync('npx playwright --version').toString().trim().split('')[1];(async()=>{constcaps={'os':'os x','os_version':'big sur','browser':'chrome',// You can choose `chrome`, `edge` or `firefox` in this capability'browser_version':'latest',// We support v83 and above. You can choose `latest`, `latest-beta`, `latest-1`, `latest-2` and so on, in this capability'browserstack.username':process.env.BROWSERSTACK_USERNAME||'YOUR_USERNAME','browserstack.accessKey':process.env.BROWSERSTACK_ACCESS_KEY||'YOUR_ACCESS_KEY','browserstack.geoLocation':"FR",'project':'My First Project','build':'playwright-build-1','name':'My First Test',// The name of your test and build. See browserstack.com/docs/automate/playwright/organize tests for more details'buildTag':'reg','resolution':'1280x1024','browserstack.local':'true','browserstack.localIdentifier':'local_connection_name','browserstack.playwrightVersion':'1.latest','client.playwrightVersion':'1.latest''browserstack.debug':'true',// enabling visual logs'browserstack.console':'info'// Enabling Console logs for the test'browserstack.networkLogs':'true'// Enabling network logs for the test'browserstack.interactiveDebugging':'true',};constbrowser=awaitchromium.connect({wsEndpoint:`wss://cdp.browserstack.com/playwright?caps=${encodeURIComponent(JSON.stringify(caps))}`,});constpage=awaitbrowser.newPage();awaitpage.goto('https://www.google.com/ncr');constelement=awaitpage.$('[aria-label="Search"]');awaitelement.click();awaitelement.type('BrowserStack');awaitelement.press('Enter');consttitle=awaitpage.title('');console.log(title);try{expect(title).to.equal("BrowserStack - Google Search",'Expected page title is incorrect!');// following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each testawaitpage.evaluate(_=>{},`browserstack_executor: ${JSON.stringify({action:'setSessionStatus',arguments:{status:'passed',reason:'Title matched'}})}`);}catch{awaitpage.evaluate(_=>{},`browserstack_executor: ${JSON.stringify({action:'setSessionStatus',arguments:{status:'failed',reason:'Title did not match'}})}`);}awaitbrowser.close();})();
// PlaywrightTest.javapackagecom.browserstack;importcom.google.gson.JsonObject;importcom.microsoft.playwright.*;importjava.net.URLEncoder;publicclassPlaywrightTest{publicstaticvoidmain(String[]args){try(Playwrightplaywright=Playwright.create()){JsonObjectcapabilitiesObject=newJsonObject();capabilitiesObject.addProperty("os","osx");capabilitiesObject.addProperty("os_version","catalina");capabilitiesObject.addProperty("browser","chrome");// allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit`capabilitiesObject.addProperty("browser_version","latest");capabilitiesObject.addProperty("browserstack.username","BROWSERSTACK_USERNAME");capabilitiesObject.addProperty("browserstack.accessKey","BROWSERSTACK_ACCESS_KEY");capabilitiesObject.addProperty("browserstack.geoLocation","FR");capabilitiesObject.addProperty("project","My First Project");capabilitiesObject.addProperty("build","playwright-java-1");capabilitiesObject.addProperty("name","Playwright first single test");capabilitiesObject.addProperty("buildTag","reg");capabilitiesObject.addProperty("resolution","1280x1024");capabilitiesObject.addProperty("browserstack.local","true");capabilitiesObject.addProperty("browserstack.localIdentifier","local_connection_name");capabilitiesObject.addProperty("browserstack.playwrightVersion","1.latest");capabilitiesObject.addProperty("client.playwrightVersion","1.latest");capabilitiesObject.addProperty("browserstack.debug","true");capabilitiesObject.addProperty("browserstack.console","info");browserstackOptions.Add("browserstack.interactiveDebugging","true");capabilitiesObject.addProperty("browserstack.networkLogs","true");BrowserTypechromium=playwright.chromium();Stringcaps=URLEncoder.encode(capabilitiesObject.toString(),"utf-8");Stringws_endpoint="wss://cdp.browserstack.com/playwright?caps="+caps;Browserbrowser=chromium.connect(ws_endpoint);Pagepage=browser.newPage();try{page.navigate("https://www.google.co.in/");Locatorlocator=page.locator("[aria-label='Search']");locator.click();page.fill("[aria-label='Search']","BrowserStack");page.locator("[aria-label='Google Search'] >> nth=0").click();Stringtitle=page.title();if(title.equals("BrowserStack - Google Search")){// following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each testmarkTestStatus("passed","Title matched",page);}else{markTestStatus("failed","Title did not match",page);}}catch(Exceptionerr){markTestStatus("failed",err.getMessage(),page);}browser.close();}catch(Exceptionerr){System.out.println(err);}}publicstaticvoidmarkTestStatus(Stringstatus,Stringreason,Pagepage){Objectresult;result=page.evaluate("_ => {}","browserstack_executor: { \"action\": \"setSessionStatus\", \"arguments\": { \"status\": \""+status+"\", \"reason\": \""+reason+"\"}}");}}
# playwright-test.py
importjsonimporturllibimportsubprocessfromplaywright.sync_apiimportsync_playwrightdesired_cap={'os':'osx','os_version':'catalina','browser':'chrome',# allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit`
'browser_version':'latest',# this capability is valid only for branded `chrome` and `edge` browsers and you can specify any browser version like `latest`, `latest-beta`, `latest-1` and so on.
'browserstack.username':'BROWSERSTACK_USERNAME','browserstack.accessKey':'BROWSERSTACK_ACCESS_KEY','browserstack.geoLocation':'FR','project':'My First Project','build':'playwright-python-1','name':'My First Test','buildTag':'reg','resolution':'1280x1024','browserstack.local':'true','browserstack.localIdentifier':'local_connection_name','browserstack.playwrightVersion':'1.latest','client.playwrightVersion':'1.latest''browserstack.debug':'true',# enabling visual logs
'browserstack.console':'info',# Enabling Console logs for the test
'browserstack.networkLogs':'true',# Enabling network logs for the test
'browserstack.interactiveDebugging':'true',}defrun_session(playwright):clientPlaywrightVersion=str(subprocess.getoutput('playwright --version')).strip().split(" ")[1]desired_cap['client.playwrightVersion']=clientPlaywrightVersioncdpUrl='wss://cdp.browserstack.com/playwright?caps='+urllib.parse.quote(json.dumps(desired_cap))browser=playwright.chromium.connect(cdpUrl)page=browser.new_page()try:page.goto("https://www.google.co.in/")page.fill("[aria-label='Search']",'Browserstack')locator=page.locator("[aria-label='Google Search'] >> nth=0")locator.click()title=page.title()iftitle=="Browserstack - Google Search":# following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each test
mark_test_status("passed","Title matched",page)else:mark_test_status("failed","Title did not match",page)exceptExceptionaserr:mark_test_status("failed",str(err),page)browser.close()defmark_test_status(status,reason,page):page.evaluate("_ => {}","browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\""+status+"\", \"reason\": \""+reason+"\"}}");withsync_playwright()asplaywright:run_session(playwright)
// PlaywrightTest.csusingMicrosoft.Playwright;usingSystem.Threading.Tasks;usingSystem;usingSystem.Collections.Generic;usingNewtonsoft.Json;classPlaywrightTest{publicstaticasyncTaskmain(string[]args){usingvarplaywright=awaitPlaywright.CreateAsync();Dictionary<string,string>browserstackOptions=newDictionary<string,string>();browserstackOptions.Add("os","osx");browserstackOptions.Add("os_version","catalina");browserstackOptions.Add("browser","chrome");// allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit`browserstackOptions.Add("browser_version","latest");browserstackOptions.Add("browserstack.username","BROWSERSTACK_USERNAME");browserstackOptions.Add("browserstack.accessKey","BROWSERSTACK_ACCESS_KEY");browserstackOptions.Add("geoLocation","FR");browserstackOptions.Add("project","Playwright first sample test");browserstackOptions.Add("name","Playwright first sample test");browserstackOptions.Add("build","playwright-dotnet-1");browserstackOptions.Add("buildTag","reg");browserstackOptions.Add("resolution","1280x1024");browserstackOptions.Add("browserstack.local","true");browserstackOptions.Add("browserstack.localIdentifier","local_connection_name");browserstackOptions.Add("browserstack.playwrightVersion","1.latest");browserstackOptions.Add("client.playwrightVersion","1.latest");browserstackOptions.Add("browserstack.debug","true");browserstackOptions.Add("browserstack.interactiveDebugging","true");browserstackOptions.Add("browserstack.console","info");browserstackOptions.Add("browserstack.networkLogs","true");stringcapsJson=JsonConvert.SerializeObject(browserstackOptions);stringcdpUrl="wss://cdp.browserstack.com/playwright?caps="+Uri.EscapeDataString(capsJson);awaitusingvarbrowser=awaitplaywright.Chromium.ConnectAsync(cdpUrl);varpage=awaitbrowser.NewPageAsync();try{awaitpage.GotoAsync("https://www.google.co.in/");awaitpage.Locator("[aria-label='Search']").ClickAsync();awaitpage.FillAsync("[aria-label='Search']","BrowserStack");awaitpage.Locator("[aria-label='Google Search'] >> nth=0").ClickAsync();vartitle=awaitpage.TitleAsync();if(title=="BrowserStack - Google Search"){// following line of code is responsible for marking the status of the test on BrowserStack as 'passed'. You can use this code in your after hook after each testawaitMarkTestStatus("passed","Title matched",page);}else{awaitMarkTestStatus("failed","Title did not match",page);}}catch(Exceptionerr){awaitMarkTestStatus("failed",err.Message,page);}awaitbrowser.CloseAsync();}publicstaticasyncTaskMarkTestStatus(stringstatus,stringreason,IPagepage){awaitpage.EvaluateAsync("_ => {}","browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\":\""+status+"\", \"reason\": \""+reason+"\"}}");}}
The following table lists the supported Playwright capabilities and how they must be defined in your tests:
Capability
Description
os
Set the operating system on which you want to run your test Eg.Windows or OS X
Set the browser you want to use for your test. For branded browsers, use: chrome or edge. The browser_version capability is applicable only when using a branded browser.
For Playwrightβs bundled browsers, use: playwright-chromium, playwright-firefox or playwright-webkit.
Set the browser version for your test Chrome: 83 and above Edge: 83 and above It is recommended that you use latest, latest-1, latest-2, latest-beta and so on, to test on the latest n versions of the required browser.
Automatically capture screenshots for every Playwright command executed during your test. It helps debug the exact step and how the page was rendered when the failure occurred.
Defaults to False. Set True to enable.
browserstack.video
Provides a video recording of the actions performed during the test.