Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated with the Android config #3

Merged
merged 13 commits into from
Aug 4, 2023
Merged
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@

- To run a sample test, run `npm run sample-test`

## Running your tests on mobile

- To run a sample test, run `npm run mobile-test`

## Run tests on locally hosted websites
* Run `npm run sample-local-test`

Expand Down
54 changes: 28 additions & 26 deletions browserstack.config.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
const base = require('@playwright/test');
const cp = require('child_process');
const base = require("@playwright/test");
const cp = require("child_process");
const clientPlaywrightVersion = cp
.execSync('npx playwright --version')
.execSync("npx playwright --version")
.toString()
.trim()
.split(' ')[1];
const BrowserStackLocal = require('browserstack-local');
const util = require('util');
.split(" ")[1];
const BrowserStackLocal = require("browserstack-local");
const util = require("util");

// BrowserStack Specific Capabilities.
// Set 'browserstack.local:true For Local testing
const caps = {
browser: 'chrome',
os: 'osx',
os_version: 'catalina',
name: 'My first playwright test',
build: 'playwright-build',
'browserstack.username': process.env.BROWSERSTACK_USERNAME || 'USERNAME',
'browserstack.accessKey': process.env.BROWSERSTACK_ACCESS_KEY || 'ACCESSKEY',
'browserstack.local': process.env.BROWSERSTACK_LOCAL || true,
'client.playwrightVersion': clientPlaywrightVersion,
browser: "chrome",
os: "osx",
os_version: "catalina",
name: "My first playwright test",
build: "playwright-build",
"browserstack.username": process.env.BROWSERSTACK_USERNAME || "USERNAME",
"browserstack.accessKey": process.env.BROWSERSTACK_ACCESS_KEY || "ACCESSKEY",
"browserstack.local": process.env.BROWSERSTACK_LOCAL || true,
"client.playwrightVersion": clientPlaywrightVersion,
};

exports.bsLocal = new BrowserStackLocal.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 || 'ACCESSKEY',
key: process.env.BROWSERSTACK_ACCESS_KEY || "ACCESSKEY",
};

// Patching the capabilities dynamically according to the project name.
Expand All @@ -36,17 +36,19 @@ const patchCaps = (name, title) => {
let [browser, browser_version] = browerCaps.split(/@/);
let osCapsSplit = osCaps.split(/ /);
let os = osCapsSplit.shift();
let os_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';
let os_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;
};

exports.getCdpEndpoint = (name, title) => {
patchCaps(name, title)
const cdpUrl = `wss://cdp.browserstack.com/playwright?caps=${encodeURIComponent(JSON.stringify(caps))}`
console.log(`--> ${cdpUrl}`)
return cdpUrl;
}
patchCaps(name, title);
const cdpUrl = `wss://cdp.browserstack.com/playwright?caps=${encodeURIComponent(
JSON.stringify(caps)
)}`;
console.log(`--> ${cdpUrl}`);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can remove this console.log

return cdpUrl;
};
12 changes: 6 additions & 6 deletions global-setup.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
// global-setup.js
const { bsLocal, BS_LOCAL_ARGS } = require('./browserstack.config');
const { promisify } = require('util');
const { bsLocal, BS_LOCAL_ARGS } = require("./browserstack.config");
const { promisify } = require("util");
const sleep = promisify(setTimeout);
const redColour = '\x1b[31m';
const whiteColour = '\x1b[0m';
const redColour = "\x1b[31m";
const whiteColour = "\x1b[0m";
module.exports = async () => {
console.log('Starting BrowserStackLocal ...');
console.log("Starting BrowserStackLocal ...");
// Starts the Local instance with the required arguments
let localResponseReceived = false;
bsLocal.start(BS_LOCAL_ARGS, (err) => {
Expand All @@ -14,7 +14,7 @@ module.exports = async () => {
`${redColour}Error starting BrowserStackLocal${whiteColour}`
);
} else {
console.log('BrowserStackLocal Started');
console.log("BrowserStackLocal Started");
}
localResponseReceived = true;
});
Expand Down
8 changes: 4 additions & 4 deletions global-teardown.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// global-teardown.js
const { bsLocal } = require('./browserstack.config');
const { promisify } = require('util');
const { bsLocal } = require("./browserstack.config");
const { promisify } = require("util");
const sleep = promisify(setTimeout);
module.exports = async () => {
// Stop the Local instance after your test run is completed, i.e after driver.quit
Expand All @@ -9,10 +9,10 @@ module.exports = async () => {
if (bsLocal && bsLocal.isRunning()) {
bsLocal.stop(() => {
localStopped = true;
console.log('Stopped BrowserStackLocal');
console.log("Stopped BrowserStackLocal");
});
while (!localStopped) {
await sleep(1000);
}
}
}
};
113 changes: 113 additions & 0 deletions mobile-fixture.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
const base = require("@playwright/test");
const cp = require("child_process");
const { _android } = require("playwright");
const clientPlaywrightVersion = cp
.execSync("npx playwright --version")
.toString()
.trim()
.split(" ")[1];
const BrowserStackLocal = require("browserstack-local");
const util = require("util");
const { test } = require("./browserstack.config");

// BrowserStack Specific Capabilities.
// Set 'browserstack.local:true For Local testing
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Set 'browserstack.local:true For Local testing
// Set "browserstack.local" as true in caps below to enable Local testing

Review this with product

const caps = {
osVersion: "13.0",
deviceName: "Samsung Galaxy S23", // "Samsung Galaxy S22 Ultra", "Google Pixel 7 Pro", "OnePlus 9", etc.
browserName: "chrome",
realMobile: "true",
name: "My android playwright test",
build: "playwright-build-1",
"browserstack.username": process.env.BROWSERSTACK_USERNAME || "<USERNAME>",
"browserstack.accessKey":
process.env.BROWSERSTACK_ACCESS_KEY || "<ACCESS_KEY>",
};

exports.bsLocal = new BrowserStackLocal.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 || "ACCESSKEY",
};

// Patching the capabilities dynamically according to the project name.
const patchMobileCaps = (name, title) => {
let combination = name.split(/@browserstack/)[0];
let [browerCaps, osCaps] = combination.split(/:/);
let [browser, deviceName] = browerCaps.split(/@/);
let osCapsSplit = osCaps.split(/ /);
let os = osCapsSplit.shift();
let osVersion = osCapsSplit.join(" ");
caps.browser = browser ? browser : "chrome";
caps.deviceName = deviceName ? deviceName : "Samsung Galaxy S22 Ultra";
caps.osVersion = osVersion ? osVersion : "12.0";
caps.name = title;
caps.realMobile = "true";
};

exports.test = base.test.extend({
page: async ({ baseURL }, use, testInfo) => {
if (testInfo.project.name.match(/browserstack/)) {
patchMobileCaps(
testInfo.project.name,
`${testInfo.file} - ${testInfo.title}`
);
const device = await base._android.connect(
`wss://cdp.browserstack.com/playwright?caps=${encodeURIComponent(
JSON.stringify(caps)
)}`
);
await device.shell("am force-stop com.android.chrome");
const context = await device.launchBrowser({
baseURL: baseURL,
});
const page = await context.newPage();
await use(page);

await context.close();
await device.close();
}
},

beforeEach: [
async ({ page }, use) => {
await page
.context()
.tracing.start({ screenshots: true, snapshots: true, sources: true });
await use();
},
{ auto: true },
],

afterEach: [
async ({ page }, use, testInfo) => {
await use();
if (testInfo.status == "failed") {
await page
.context()
.tracing.stop({ path: `${testInfo.outputDir}/trace.zip` });
await page.screenshot({ path: `${testInfo.outputDir}/screenshot.png` });
await testInfo.attach("screenshot", {
path: `${testInfo.outputDir}/screenshot.png`,
contentType: "image/png",
});
await testInfo.attach("trace", {
path: `${testInfo.outputDir}/trace.zip`,
contentType: "application/zip",
});
}
},
{ auto: true },
],
});

exports.getMobileEndpoint = (name, title) => {
patchMobileCaps(name, title);
delete caps.os_version;
delete caps.os;
const cdpUrl = `wss://cdp.browserstack.com/playwright?caps=${encodeURIComponent(
JSON.stringify(caps)
)}`;
return cdpUrl;
};
9 changes: 6 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@
"description": "",
"main": "index.js",
"scripts": {
"sample-local-test":"npx playwright test tests/local_test.js",
"sample-test":"npx playwright test tests/sample_test.js"
"sample-local-test": "npx playwright test tests/local_test.js",
"sample-test": "npx playwright test tests/sample_test.js",
"mobile-test": "npx playwright test tests/mobile_test.js --project='chrome@Samsung Galaxy S22:13@browserstack'"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@playwright/test": "^1.29.1",
"browserstack-local": "^1.5.1"
"browserstack-local": "^1.5.1",
"playwright": "1.29.1",
"prettier": "2.8.8"
}
}
55 changes: 35 additions & 20 deletions playwright.config.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
// @ts-check
const { devices } = require('@playwright/test');
const { getCdpEndpoint } = require('./browserstack.config.js')
const { devices } = require("@playwright/test");
const { getCdpEndpoint } = require("./browserstack.config.js");

/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// require('dotenv').config();


/**
* @see https://playwright.dev/docs/test-configuration
* @type {import('@playwright/test').PlaywrightTestConfig}
*/
const config = {
testDir: './tests',
testMatch: '**/*.js',
globalSetup: require.resolve('./global-setup'),
globalTeardown: require.resolve('./global-teardown'),
testDir: "./tests",
testMatch: "**/*.js",

globalSetup: require.resolve("./global-setup"),
globalTeardown: require.resolve("./global-teardown"),

/* Maximum time one test can run for. */
timeout: 90 * 1000,
Expand All @@ -27,7 +26,7 @@ const config = {
* Maximum time expect() should wait for the condition to be met.
* For example in `await expect(locator).toHaveText();`
*/
timeout: 5000
timeout: 5000,
},
/* Run tests in files in parallel */
fullyParallel: true,
Expand All @@ -38,7 +37,7 @@ const config = {
/* Opt out of parallel tests on CI. */
workers: process.env.CI ? 1 : undefined,
/* Reporter to use. See https://playwright.dev/docs/test-reporters */
reporter: 'html',
reporter: "html",
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */
Expand All @@ -47,30 +46,46 @@ const config = {
// baseURL: 'http://localhost:3000',

/* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'on-first-retry',
trace: "on-first-retry",
},

/* Configure projects for major browsers */
projects: [
{
name: 'chrome@latest:Windows 11',
name: "chrome@latest:Windows 11",
use: {
connectOptions: {
wsEndpoint: getCdpEndpoint("chrome@latest:Windows 11", "test1"),
},
},
},
{
name: "playwright-webkit@latest:OSX Ventura",
use: {
connectOptions: { wsEndpoint: getCdpEndpoint('chrome@latest:Windows 11','test1') },
connectOptions: {
wsEndpoint: getCdpEndpoint(
"playwright-webkit@latest:OSX Ventura",
"test2"
),
},
},
}
,
},
{
name: 'playwright-webkit@latest:OSX Ventura',
name: "playwright-firefox:Windows 11",
use: {
connectOptions: { wsEndpoint: getCdpEndpoint('playwright-webkit@latest:OSX Ventura', 'test2') }
connectOptions: {
wsEndpoint: getCdpEndpoint("playwright-firefox:Windows 11", "test3"),
},
},
},
{
name: 'playwright-firefox:Windows 11',
name: "chrome@Samsung Galaxy S22:13@browserstack",
use: {
connectOptions: { wsEndpoint: getCdpEndpoint('playwright-firefox:Windows 11', 'test3') }
baseURL: "https://www.bstackdemo.com/",
browserName: "chromium",
channel: "chrome",
},
}
},
],

/* Folder for test artifacts such as screenshots, videos, traces, etc. */
Expand Down
Loading