Skip to main content

Test private websites using Playwright

A guide to running your Playwright tests on your privately hosted websites.

BrowserStack enables you to run automated tests on your internal development environments, on localhost, and from behind a corporate firewall. This feature is called Local Testing.

Local Testing establishes a secure connection between your machine and the BrowserStack cloud. Once you set up Local Testing, all URLs work out of the box, including HTTPS URLs and those behind a proxy or firewall. Learn more about how Local Testing works.

Run your first Playwright local test

Local Testing can be enabled through two methods and both of them have been detailed as follows:

Note: Testing on BrowserStack requires username and access key that can be found in account settings.
If you have not created an account yet, you can sign up for a Free Trial or purchase a plan.

Local testing connection can be set up using the npm package for BrowserStack Local. Use the following steps to run our sample test:

  • Step 1: Clone our sample repository and install dependencies

    Check out the GitHub repository to access all the sample tests used in the Getting Started section. The first step is to download this repository on your system and install the dependencies as follows:

    # The following command will clone the repository on your system
    
    git clone https://github.com/browserstack/playwright-browserstack.git
    cd playwright-browserstack
    
    # The following command will install the required dependencies
    npm install
    

    The important dependency for Local Testing is browserstack-local and you need to install it in your project using the following command:

    npm i --save-dev browserstack-local
    
  • Step 2: Configuring BrowserStack credentials

    All our sample scripts need your BrowserStack credentials to run. Set the environment variables BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY with your credentials using the following command:

    export BROWSERSTACK_USERNAME="YOUR_USERNAME"
    export BROWSERSTACK_ACCESS_KEY="YOUR_ACCESS_KEY"
    

    Alternatively, you can set your credentials in the browserstack.username and browserstack.accessKey capabilities in the single_test.js file (and all other spec files) in the sample repository.

  • Step 3: Run your first Local test

    After you have configured the credentials and installed the npm dependencies, you can run your local test on BrowserStack using the following command:

    node local_test_using_bindings.js
    

Local testing connection can be set up using the npm package for BrowserStack Local. Use the following steps to run our sample test:

  • Step 1: Clone our sample repository and install dependencies

    Check out the GitHub repository to access all the sample tests used in the Getting Started section. The first step is to download this repository on your system and install the dependencies as follows:

    # The following command will clone the repository on your system
    
    git clone https://github.com/browserstack/playwright-browserstack.git
    cd playwright-browserstack
    npm install
    
  • Step 2: Configuring BrowserStack credentials

    All our sample scripts need your BrowserStack credentials to run. Set the environment variables BROWSERSTACK_USERNAME and BROWSERSTACK_ACCESS_KEY with your credentials as follows:

    export BROWSERSTACK_USERNAME="YOUR_USERNAME"
    export BROWSERSTACK_ACCESS_KEY="YOUR_ACCESS_KEY"
    

    Alternatively, your can set your credentials in the browserstack.username and browserstack.accessKey capabilities in the single_test.js file (and all other spec files) in the sample repository.

  • Step 3: Download the BrowserStack Local binary from the following links (depending on your local machine’s environment):
  • Step 4: Start the binary

    Once you have downloaded and unzipped the file, you can initiate the binary by running the following command:

    ./BrowserStackLocal --key YOUR_ACCESS_KEY
    

    You can run the BrowserStack Local binary using the available configurable options that may suit your use case.

  • Step 5: Verify Local connection established

    Once you see the “[SUCCESS] You can now access your local server(s) in our remote browser” message in your terminal, your local testing connection is considered established.

  • Step 6: Run your sample Local test

    node local_test.js
    

After your test runs successfully, check out the BrowserStack Automate dashboard to view the results.

Details of your first test

This section explains the details of the test that you just ran, and the changes that you need to make in your existing Playwright scripts to make them run on BrowserStack using both the approaches.

When you run your test command, the test script:

  • Starts the latest version of the Chrome browser.
  • Opens the Google search home page.
  • Performs a search for the term “BrowserStack”.
  • Marks the test as passed or failed based on the assertions.

Check out the GitHub repository for more information.

local_test_using_bindings.js
const { chromium } = require('playwright');
const BrowserStackLocal = require('browserstack-local');

const cp = require('child_process');
const clientPlaywrightVersion = cp.execSync('npx playwright --version').toString().trim().split(' ')[1];

const bsLocal = new BrowserStackLocal.Local();

// replace YOUR_ACCESS_KEY with your key. You can also set an environment variable - "BROWSERSTACK_ACCESS_KEY".
const BS_LOCAL_ARGS = {
    'key': process.env.BROWSERSTACK_ACCESS_KEY || 'YOUR_ACCESS_KEY'
};

/**
 * Mark test status on BrowserStack.
 *
 * @param {Page} page - Page object created by Puppeteer context.
 * @param {String} status - Status string can be either passed|failed.
 * @param {String} reason - Explanatory reason for the status marked.
 * @return {Promise<String>} Stringified response from BrowserStack regarding the
 * execution of the jsExecutor.
 */
function markTest(page, status, reason) {
    return page.evaluate(
        _ => {},
        `browserstack_executor: ${JSON.stringify({
            action: 'setSessionStatus',
            arguments: { status, reason }
        })}`);
}

/**
 * Driver Test Function.
 *
 * @async
 * @return {Promise<void>}
 */
async function testFn() {
    console.log('Started BrowserStackLocal');

    // Check if BrowserStack local instance is running
    console.log(`BrowserStackLocal running: ${bsLocal.isRunning()}`);

    const caps = {
        'browser': 'edge',  // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit`
        'os': 'osx',
        'os_version': 'catalina',
        'name': 'Playwright sample Local test',
        'build': 'playwright-build-3',
        'browserstack.local': 'true',
        'browserstack.username': process.env.BROWSERSTACK_USERNAME || 'YOUR_USERNAME',
        'browserstack.accessKey': process.env.BROWSERSTACK_ACCESS_KEY || 'YOUR_ACCESS_KEY',
        'client.playwrightVersion': clientPlaywrightVersion  // Playwright version being used on your local project needs to be passed in this capability for BrowserStack to be able to map request and responses correctly
    };

    // Use `.connect()` to initiate an Automate session on BrowserStack
    const browser = await chromium.connect({
        wsEndpoint: `wss://cdp.browserstack.com/playwright?caps=${encodeURIComponent(JSON.stringify(caps))}`,
      });
    // BrowserStack specific code ends here

    const page = await browser.newPage();
    await page.goto('http://localhost:45691');
    try {
        await page.waitForFunction(
            `document
                .querySelector("body")
                .innerText
                .includes("This is an internal server for BrowserStack Local")`,
        );
        // 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
        await markTest(page, 'passed', 'Local is up and running');
    } catch {
        await markTest(page, 'failed', 'BrowserStack Local binary is not running');
    }
    await browser.close();

    // Stop the Local instance after your test run is completed, i.e after driver.quit
    bsLocal.stop(() => console.log('Stopped BrowserStackLocal'));
}

// Starts the Local instance with the required arguments
bsLocal.start(BS_LOCAL_ARGS, testFn);

When you run your test command, the test script:

  • Starts the latest version of the Chrome browser.
  • Opens the Google search home page.
  • Performs a search for the term “BrowserStack”.
  • Marks the test as passed or failed based on the assertions.

Check out the GitHub repository for more information.

local_test.js
const expect = require('chai').expect
const { chromium } = require('playwright');

const cp = require('child_process');
const clientPlaywrightVersion = cp.execSync('npx playwright --version').toString().trim().split(' ')[1];

(async () => {
  const caps = {
  	'browser': 'chrome',  // allowed browsers are `chrome`, `edge`, `playwright-chromium`, `playwright-firefox` and `playwright-webkit`
    'os': 'osx',
    'os_version': 'catalina',
    'name': 'Playwright sample Local test',
    'build': 'playwright-build-3',
    'browserstack.local': 'true',
    'browserstack.username': process.env.BROWSERSTACK_USERNAME || 'YOUR_USERNAME',
    'browserstack.accessKey': process.env.BROWSERSTACK_ACCESS_KEY || 'YOUR_ACCESS_KEY',
    'client.playwrightVersion': clientPlaywrightVersion  // Playwright version being used on your local project needs to be passed in this capability for BrowserStack to be able to map request and responses correctly
  };
  const browser = await chromium.connect({
    wsEndpoint: `wss://cdp.browserstack.com/playwright?caps=${encodeURIComponent(JSON.stringify(caps))}`,
  });
  const page = await browser.newPage();
  await page.goto('http://localhost:45454');
  const title = await page.title('');
  console.log(title);
  try {
    expect(title).to.equal("BrowserStack Local", '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 test
    await page.evaluate(_ => {}, `browserstack_executor: ${JSON.stringify({action: 'setSessionStatus',arguments: {status: 'passed',reason: 'Local connection established successfully'}})}`);
  } catch {
    await page.evaluate(_ => {}, `browserstack_executor: ${JSON.stringify({action: 'setSessionStatus',arguments: {status: 'failed',reason: 'Page title did not match'}})}`);
  }
  await browser.close();
})();
Note: Playwright tests run on BrowserStack using a client-server architecture. So, test assertions run on the client side and hence BrowserStack won’t know whether your tests have passed or failed. Learn more how to mark tests as passed or failed on BrowserStack.

You can learn more about how to make your existing Playwright scripts run on BrowserStack and you can also learn about how to run cross-browser Playwright tests in parallel.

Next Steps

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked






Thank you for your valuable feedback

Is this page helping you?

Yes
No

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked






Thank you for your valuable feedback!

Talk to an Expert
Talk to an Expert