Best JavaScript code snippet using webdriverio-monorepo
browser-options.js
Source:browser-options.js
1'use strict';2const _ = require('lodash');3const option = require('gemini-configparser').option;4const defaults = require('./defaults');5const optionsBuilder = require('./options-builder');6const utils = require('./utils');7const is = utils.is;8exports.getTopLevel = () => {9 const provideDefault = _.propertyOf(defaults);10 return buildBrowserOptions(provideDefault, {11 desiredCapabilities: optionsBuilder(provideDefault).optionalObject('desiredCapabilities')12 });13};14exports.getPerBrowser = () => {15 return buildBrowserOptions(provideTopLevelDefault, {16 desiredCapabilities: option({17 defaultValue: defaults.desiredCapabilities,18 parseEnv: JSON.parse,19 parseCli: JSON.parse,20 validate: (value, config) => {21 if (_.isNull(value) && _.isNull(config.desiredCapabilities)) {22 throw new Error('Each browser must have "desiredCapabilities" option');23 } else {24 utils.assertOptionalObject(value, 'desiredCapabilities');25 }26 },27 map: (value, config) => _.extend({}, config.desiredCapabilities, value)28 })29 });30};31function provideTopLevelDefault(name) {32 return (config) => {33 const value = config[name];34 if (_.isUndefined(value)) {35 throw new Error(`"${name}" should be set at the top level or per-browser option`);36 }37 return value;38 };39}40function buildBrowserOptions(defaultFactory, extra) {41 const options = optionsBuilder(defaultFactory);42 return _.extend(extra, {43 gridUrl: options.string('gridUrl'),44 baseUrl: option({45 defaultValue: defaultFactory('baseUrl'),46 validate: is('string', 'baseUrl'),47 map: (value, config) => {48 return config.baseUrl && !value.match(/^https?:\/\//)49 ? [config.baseUrl.replace(/\/$/, ''), value.replace(/^\//, '')].join('/')50 : value;51 }52 }),53 automationProtocol: option({54 defaultValue: defaultFactory('automationProtocol'),55 validate: (value) => {56 is('string', 'automationProtocol')(value);57 if (value !== 'webdriver' && value !== 'devtools') {58 throw new Error('"automationProtocol" must be "webdriver" or "devtools"');59 }60 }61 }),62 sessionEnvFlags: option({63 defaultValue: defaultFactory('sessionEnvFlags'),64 validate: (value) => {65 if (!_.isPlainObject(value)) {66 throw new Error('"sessionEnvFlags" must be an object');67 }68 if (_.isEmpty(value)) {69 return;70 }71 const availableSessionEnvFlags = [72 'isW3C', 'isChrome', 'isMobile', 'isIOS', 'isAndroid', 'isSauce', 'isSeleniumStandalone'73 ];74 Object.keys(value).forEach((key) => {75 if (!availableSessionEnvFlags.includes(key)) {76 throw new Error(`keys of "sessionEnvFlags" must be one of: ${availableSessionEnvFlags.join(', ')}`);77 }78 if (!_.isBoolean(value[key])) {79 throw new Error('values of "sessionEnvFlags" must be boolean');80 }81 });82 }83 }),84 sessionsPerBrowser: options.positiveInteger('sessionsPerBrowser'),85 testsPerSession: options.positiveIntegerOrInfinity('testsPerSession'),86 retry: options.nonNegativeInteger('retry'),87 shouldRetry: options.optionalFunction('shouldRetry'),88 httpTimeout: options.nonNegativeInteger('httpTimeout'),89 urlHttpTimeout: options.optionalNonNegativeInteger('urlHttpTimeout'),90 pageLoadTimeout: options.optionalNonNegativeInteger('pageLoadTimeout'),91 sessionRequestTimeout: options.optionalNonNegativeInteger('sessionRequestTimeout'),92 sessionQuitTimeout: options.optionalNonNegativeInteger('sessionQuitTimeout'),93 testTimeout: options.optionalNonNegativeInteger('testTimeout'),94 waitTimeout: options.positiveInteger('waitTimeout'),95 waitInterval: options.positiveInteger('waitInterval'),96 saveHistory: options.boolean('saveHistory'),97 screenshotOnReject: options.boolean('screenshotOnReject'),98 screenshotOnRejectTimeout: options.optionalNonNegativeInteger('screenshotOnRejectTimeout'),99 prepareBrowser: options.optionalFunction('prepareBrowser'),100 screenshotsDir: options.stringOrFunction('screenshotsDir'),101 calibrate: options.boolean('calibrate'),102 compositeImage: options.boolean('compositeImage'),103 strictTestsOrder: options.boolean('strictTestsOrder'),104 screenshotMode: option({105 defaultValue: defaultFactory('screenshotMode'),106 validate: (value) => {107 is('string', 'screenshotMode')(value);108 if (!_.includes(['fullpage', 'viewport', 'auto'], value)) {109 throw new Error('"screenshotMode" must be "fullpage", "viewport" or "auto"');110 }111 },112 map: (value, config, currentNode) => {113 if (value !== defaults.screenshotMode) {114 return value;115 }116 // Chrome mobile returns screenshots that are larger than visible viewport due to a bug:117 // https://bugs.chromium.org/p/chromedriver/issues/detail?id=2853118 // Due to this, screenshot is cropped incorrectly.119 const capabilities = _.get(currentNode, 'desiredCapabilities');120 const isAndroid = capabilities && Boolean(121 (capabilities.platformName && capabilities.platformName.match(/Android/i)) ||122 (capabilities.browserName && capabilities.browserName.match(/Android/i))123 );124 return isAndroid ? 'viewport' : value;125 }126 }),127 screenshotDelay: options.nonNegativeInteger('screenshotDelay'),128 tolerance: option({129 defaultValue: defaultFactory('tolerance'),130 parseEnv: Number,131 parseCli: Number,132 validate: (value) => utils.assertNonNegativeNumber(value, 'tolerance')133 }),134 antialiasingTolerance: option({135 defaultValue: defaultFactory('antialiasingTolerance'),136 parseEnv: Number,137 parseCli: Number,138 validate: (value) => utils.assertNonNegativeNumber(value, 'antialiasingTolerance')139 }),140 compareOpts: options.optionalObject('compareOpts'),141 buildDiffOpts: options.optionalObject('buildDiffOpts'),142 assertViewOpts: option({143 defaultValue: defaultFactory('assertViewOpts'),144 parseEnv: JSON.parse,145 parseCli: JSON.parse,146 validate: (value) => utils.assertOptionalObject(value, 'assertViewOpts'),147 map: (value) => {148 return value === defaults.assertViewOpts149 ? value150 : {...defaults.assertViewOpts, ...value};151 }152 }),153 meta: options.optionalObject('meta'),154 windowSize: option({155 defaultValue: defaultFactory('windowSize'),156 validate: (value) => {157 if (_.isNull(value)) {158 return;159 }160 if (_.isObject(value)) {161 if (_.isNumber(value.width) && _.isNumber(value.height)) {162 return;163 } else {164 throw new Error('"windowSize" must be an object with "width" and "height" keys');165 }166 }167 if (!_.isString(value)) {168 throw new Error('"windowSize" must be string, object or null');169 } else if (!/^\d+x\d+$/.test(value)) {170 throw new Error('"windowSize" should have form of <width>x<height> (i.e. 1600x1200)');171 }172 },173 map: (value) => {174 if (_.isNull(value) || _.isObject(value)) {175 return value;176 }177 const [width, height] = value.split('x').map((v) => parseInt(v, 10));178 return {width, height};179 }180 }),181 orientation: option({182 defaultValue: defaultFactory('orientation'),183 validate: (value) => {184 if (_.isNull(value)) {185 return;186 }187 is('string', 'orientation')(value);188 if (value !== 'landscape' && value !== 'portrait') {189 throw new Error('"orientation" must be "landscape" or "portrait"');190 }191 }192 }),193 waitOrientationChange: options.boolean('waitOrientationChange'),194 resetCursor: options.boolean('resetCursor'),195 outputDir: options.optionalString('outputDir'),196 agent: options.optionalObject('agent'),197 headers: options.optionalObject('headers'),198 transformRequest: options.optionalFunction('transformRequest'),199 transformResponse: options.optionalFunction('transformResponse'),200 strictSSL: options.optionalBoolean('strictSSL'),201 user: options.optionalString('user'),202 key: options.optionalString('key'),203 region: options.optionalString('region'),204 headless: options.optionalBoolean('headless')205 });...
utils.js
Source:utils.js
...137}138function isSauce(hostname, caps) {139 return Boolean(caps.extendedDebugging || caps['sauce:options'] && caps['sauce:options'].extendedDebugging);140}141function isSeleniumStandalone(caps) {142 return Boolean(caps['webdriver.remote.sessionid']);143}144function environmentDetector({145 hostname,146 capabilities,147 requestedCapabilities148}) {149 return {150 isW3C: isW3C(capabilities),151 isChrome: isChrome(capabilities),152 isMobile: isMobile(capabilities),153 isIOS: isIOS(capabilities),154 isAndroid: isAndroid(capabilities),155 isSauce: isSauce(hostname, requestedCapabilities.w3cCaps.alwaysMatch),156 isSeleniumStandalone: isSeleniumStandalone(capabilities)157 };158}159function getErrorFromResponseBody(body) {160 if (!body) {161 return new Error('Response has empty body');162 }163 if (typeof body === 'string' && body.length) {164 return new Error(body);165 }166 if (typeof body !== 'object' || !body.value) {167 return new Error('unknown error');168 }169 return new CustomRequestError(body);170}...
envDetector.js
Source:envDetector.js
...43}44function isSauce(caps) {45 return Boolean(caps.extendedDebugging || caps['sauce:options'] && caps['sauce:options'].extendedDebugging);46}47function isSeleniumStandalone(caps) {48 if (!caps) {49 return false;50 }51 return Boolean(caps['webdriver.remote.sessionid']);52}53function capabilitiesEnvironmentDetector(capabilities, automationProtocol) {54 return automationProtocol === 'devtools' ? devtoolsEnvironmentDetector(capabilities) : webdriverEnvironmentDetector(capabilities);55}56function sessionEnvironmentDetector({57 capabilities,58 requestedCapabilities59}) {60 return {61 isW3C: isW3C(capabilities),62 isChrome: isChrome(capabilities),63 isMobile: isMobile(capabilities),64 isIOS: isIOS(capabilities),65 isAndroid: isAndroid(capabilities),66 isSauce: isSauce(requestedCapabilities.w3cCaps.alwaysMatch),67 isSeleniumStandalone: isSeleniumStandalone(capabilities)68 };69}70function devtoolsEnvironmentDetector({71 browserName72}) {73 return {74 isDevTools: true,75 isW3C: true,76 isMobile: false,77 isIOS: false,78 isAndroid: false,79 isChrome: browserName === 'chrome',80 isSauce: false,81 isSeleniumStandalone: false...
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6 .remote(options)7 .init()8 .getTitle().then(function(title) {9 console.log('Title was: ' + title);10 })11 .end();
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6 .remote(options)7 .init()8 .getTitle().then(function(title) {9 console.log('Title was: ' + title);10 })11 .end();
Using AI Code Generation
1const webdriverio = require('webdriverio');2const options = { desiredCapabilities: { browserName: 'chrome' } };3const client = webdriverio.remote(options);4client.isSeleniumStandalone().then(function(isSeleniumStandalone) {5 console.log(isSeleniumStandalone);6 client.end();7});
Using AI Code Generation
1const webdriverio = require('webdriverio');2const options = {3 desiredCapabilities: {4 }5};6const client = webdriverio.remote(options);7client.isSeleniumStandalone().then((isSeleniumStandalone) => {8 console.log(isSeleniumStandalone);9});10client.isSeleniumStandalone().then((isSeleniumStandalone) => {11 console.log(isSeleniumStandalone);12});13client.end();14Example 2: isSeleniumStandalone() in Chai15const webdriverio = require('webdriverio');16const chai = require('chai');17const chaiAsPromised = require('chai-as-promised');18const expect = chai.expect;19chai.use(chaiAsPromised);20const options = {21 desiredCapabilities: {22 }23};24const client = webdriverio.remote(options);25describe('webdriver.io page', () => {26 it('should have the right title', () => {27 .getTitle().then((title) => {28 expect(title).to.equal('WebdriverIO - Selenium 2.0 javascript bindings for nodejs');29 });30 });31 it('should have the right title', () => {32 .isSeleniumStandalone().then((isSeleniumStandalone) => {33 expect(isSeleniumStandalone).to.equal(true);34 });35 });36});37client.end();38Example 3: isSeleniumStandalone() in Mocha39const webdriverio = require('webdriverio');40const assert = require('assert');41const options = {42 desiredCapabilities: {43 }44};45const client = webdriverio.remote(options);46describe('webdriver.io page', () => {47 it('should have the right title', () => {48 .getTitle().then((title) => {49 assert.equal(title, 'WebdriverIO - Selenium 2.0 javascript bindings for nodejs');50 });51 });52 it('should have the right title
Using AI Code Generation
1const webdriverio = require('webdriverio');2const options = {3 desiredCapabilities: {4 }5};6const client = webdriverio.remote(options);7client.isSeleniumStandalone().then((isSeleniumStandalone) => {8 console.log(isSeleniumStandalone);9});
Using AI Code Generation
1var webdriverio = require('webdriverio');2var options = {3 desiredCapabilities: {4 }5};6 .remote(options)7 .init()8 .isSeleniumStandalone()9 .then(function(isSeleniumStandalone) {10 if (isSeleniumStandalone) {11 console.log('Selenium Standalone is running');12 } else {13 console.log('Selenium Standalone is not running');14 }15 })16 .end();17var webdriverio = require('webdriverio');18var options = {19 desiredCapabilities: {20 }21};22 .remote(options)23 .init()24 .isMobile()25 .then(function(isMobile) {26 if (isMobile) {27 console.log('Mobile device detected');28 } else {29 console.log('No mobile device detected');30 }31 })32 .end();33var webdriverio = require('webdriverio');34var options = {35 desiredCapabilities: {36 }37};38 .remote(options)39 .init()40 .isAndroid()41 .then(function(isAndroid) {42 if (isAndroid) {43 console.log('Android device detected');44 } else {45 console.log('No Android device detected');46 }47 })48 .end();
Using AI Code Generation
1const WebdriverIO = require('webdriverio');2const wdio = new WebdriverIO();3console.log(wdio.isSeleniumStandalone());4const WebdriverIO = require('webdriverio');5console.log(WebdriverIO.isSeleniumStandalone());6const WebdriverIO = require('webdriverio');7const wdio = new WebdriverIO();8console.log(wdio.isSeleniumStandalone());9const WebdriverIO = require('webdriverio');10console.log(WebdriverIO.isSeleniumStandalone());11const WebdriverIO = require('webdriverio');12const wdio = new WebdriverIO();13console.log(wdio.isSeleniumStandalone());14const WebdriverIO = require('webdriverio');15console.log(WebdriverIO.isSeleniumStandalone());16const WebdriverIO = require('webdriverio');17const wdio = new WebdriverIO();18console.log(wdio.isSeleniumStandalone());19const WebdriverIO = require('webdriverio');20console.log(WebdriverIO.isSeleniumStandalone());21const WebdriverIO = require('webdriverio');22const wdio = new WebdriverIO();23console.log(wdio.isSeleniumStandalone());24const WebdriverIO = require('webdriverio');25console.log(WebdriverIO.isSeleniumStandalone());
Using AI Code Generation
1const webdriverio = require('webdriverio');2const {remote} = require('webdriverio');3const chrome = require('selenium-standalone');4const chromedriver = require('chromedriver');5const options = {6 capabilities: {7 }8};9chrome.start(function(err, child) {10 if (err) {11 throw err;12 }13 const selenium = child;14 const client = webdriverio.remote(options);15 client.init().then(() => {16 console.log('Selenium Standalone is running');17 selenium.kill();18 });19});20const {config} = require('./wdio.shared.conf');21const chrome = require('selenium-standalone');22const chromedriver = require('chromedriver');
Using AI Code Generation
1const webdriverio = require('webdriverio');2const options = {3 desiredCapabilities: {4 },5};6webdriverio.remote(options).init()7 .getTitle().then(function(title) {8 console.log('Title was: ' + title);9 })10 .end();
Using AI Code Generation
1require("webdriverio");2const webdriverio = require("webdriverio");3const isSeleniumStandalone = () => {4 return process.env.SELENIUM_DRIVER === "selenium-standalone";5};6const isHeadless = () => {7 return process.env.HEADLESS === "true";8};9const isSauceLabs = () => {10 return process.env.SAUCELABS === "true";11};12const isBrowserStack = () => {13 return process.env.BROWSERSTACK === "true";14};15const isTestingBot = () => {16 return process.env.TESTINGBOT === "true";17};18const isCrossBrowserTesting = () => {19 return process.env.CROSSBROWSERTESTING === "true";20};21const isSeleniumGrid = () => {22 return process.env.SELENIUM_GRID === "true";23};24const isSauceLabsOrBrowserStack = () => {25 return isSauceLabs() || isBrowserStack();26};27const isSauceLabsOrTestingBot = () => {28 return isSauceLabs() || isTestingBot();29};30const isSauceLabsOrCrossBrowserTesting = () => {31 return isSauceLabs() || isCrossBrowserTesting();32};33const isSauceLabsOrBrowserStackOrTestingBot = () => {34 return isSauceLabs() || isBrowserStack() || isTestingBot();35};36const isSauceLabsOrBrowserStackOrCrossBrowserTesting = () => {37 return isSauceLabs() || isBrowserStack() || isCrossBrowserTesting();38};39const isSauceLabsOrBrowserStackOrTestingBotOrCrossBrowserTesting = () => {40 return (41 isSauceLabs() ||42 isBrowserStack() ||43 isTestingBot() ||44 isCrossBrowserTesting()45 );46};47const isSauceLabsOrBrowserStackOrTestingBotOrCrossBrowserTestingOrSeleniumGrid = () => {48 return (49 isSauceLabs() ||50 isBrowserStack() ||51 isTestingBot() ||52 isCrossBrowserTesting() ||53 isSeleniumGrid()54 );55};56const isSauceLabsOrBrowserStackOrTestingBotOrCrossBrowserTestingOrSeleniumGridOrSeleniumStandalone = () => {57 return (58 isSauceLabs() ||59 isBrowserStack() ||60 isTestingBot() ||
Wondering what could be a next-gen browser and mobile test automation framework that is also simple and concise? Yes, that’s right, it's WebdriverIO. Since the setup is very easy to follow compared to Selenium testing configuration, you can configure the features manually thereby being the center of attraction for automation testing. Therefore the testers adopt WedriverIO to fulfill their needs of browser testing.
Learn to run automation testing with WebdriverIO tutorial. Go from a beginner to a professional automation test expert with LambdaTest WebdriverIO tutorial.
Running Your First Automation Script - Learn the steps involved to execute your first Test Automation Script using WebdriverIO since the setup is very easy to follow and the features can be configured manually.
Selenium Automation With WebdriverIO - Read more about automation testing with WebdriverIO and how it supports both browsers and mobile devices.
Browser Commands For Selenium Testing - Understand more about the barriers faced while working on your Selenium Automation Scripts in WebdriverIO, the ‘browser’ object and how to use them?
Handling Alerts & Overlay In Selenium - Learn different types of alerts faced during automation, how to handle these alerts and pops and also overlay modal in WebdriverIO.
How To Use Selenium Locators? - Understand how Webdriver uses selenium locators in a most unique way since having to choose web elements very carefully for script execution is very important to get stable test results.
Deep Selectors In Selenium WebdriverIO - The most popular automation testing framework that is extensively adopted by all the testers at a global level is WebdriverIO. Learn how you can use Deep Selectors in Selenium WebdriverIO.
Handling Dropdown In Selenium - Learn more about handling dropdowns and how it's important while performing automated browser testing.
Automated Monkey Testing with Selenium & WebdriverIO - Understand how you can leverage the amazing quality of WebdriverIO along with selenium framework to automate monkey testing of your website or web applications.
JavaScript Testing with Selenium and WebdriverIO - Speed up your Javascript testing with Selenium and WebdriverIO.
Cross Browser Testing With WebdriverIO - Learn more with this step-by-step tutorial about WebdriverIO framework and how cross-browser testing is done with WebdriverIO.
Get 100 minutes of automation test minutes FREE!!