UNPKG

codeceptjs

Version:

Modern Era Acceptance Testing Framework for NodeJS

1,631 lines (1,440 loc) 103 kB
let webdriverio; const assert = require('assert'); const path = require('path'); const requireg = require('requireg'); const Helper = require('../helper'); const stringIncludes = require('../assert/include').includes; const { urlEquals, equals } = require('../assert/equal'); const { debug } = require('../output'); const empty = require('../assert/empty').empty; const truth = require('../assert/truth').truth; const { xpathLocator, fileExists, decodeUrl, chunkArray, convertCssPropertiesToCamelCase, screenshotOutputFolder, getNormalizedKeyAttributeValue, modifierKeys, } = require('../utils'); const { isColorProperty, convertColorToRGBA, } = require('../colorUtils'); const ElementNotFound = require('./errors/ElementNotFound'); const ConnectionRefused = require('./errors/ConnectionRefused'); const Locator = require('../locator'); const webRoot = 'body'; /** * WebDriver helper which wraps [webdriverio](http://webdriver.io/) library to * manipulate browser using Selenium WebDriver or PhantomJS. * * WebDriver requires [Selenium Server and ChromeDriver/GeckoDriver to be installed](http://codecept.io/quickstart/#prepare-selenium-server). * * ### Configuration * * This helper should be configured in codecept.json or codecept.conf.js * * * `url`: base url of website to be tested. * * `browser`: browser in which to perform testing. * * `host`: (optional, default: localhost) - WebDriver host to connect. * * `port`: (optional, default: 4444) - WebDriver port to connect. * * `protocol`: (optional, default: http) - protocol for WebDriver server. * * `path`: (optional, default: /wd/hub) - path to WebDriver server, * * `restart`: (optional, default: true) - restart browser between tests. * * `smartWait`: (optional) **enables [SmartWait](http://codecept.io/acceptance/#smartwait)**; wait for additional milliseconds for element to appear. Enable for 5 secs: "smartWait": 5000. * * `disableScreenshots`: (optional, default: false) - don't save screenshots on failure. * * `fullPageScreenshots` (optional, default: false) - make full page screenshots on failure. * * `uniqueScreenshotNames`: (optional, default: false) - option to prevent screenshot override if you have scenarios with the same name in different suites. * * `keepBrowserState`: (optional, default: false) - keep browser state between tests when `restart` is set to false. * * `keepCookies`: (optional, default: false) - keep cookies between tests when `restart` set to false. * * `windowSize`: (optional) default window size. Set to `maximize` or a dimension in the format `640x480`. * * `waitForTimeout`: (optional, default: 1000) sets default wait time in *ms* for all `wait*` functions. * * `desiredCapabilities`: Selenium's [desired * capabilities](https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities). * * `manualStart`: (optional, default: false) - do not start browser before a test, start it manually inside a helper * with `this.helpers["WebDriver"]._startBrowser()`. * * `timeouts`: [WebDriver timeouts](http://webdriver.io/docs/timeouts.html) defined as hash. * * Example: * * ```js * { * helpers: { * WebDriver : { * smartWait: 5000, * browser: "chrome", * restart: false, * windowSize: "maximize", * timeouts: { * "script": 60000, * "page load": 10000 * } * } * } * } * ``` * * Additional configuration params can be used from [webdriverio * website](http://webdriver.io/guide/getstarted/configuration.html). * * ### Headless Chrome * * ```js * { * helpers: { * WebDriver : { * url: "http://localhost", * browser: "chrome", * desiredCapabilities: { * chromeOptions: { * args: [ "--headless", "--disable-gpu", "--no-sandbox" ] * } * } * } * } * } * ``` * * ### Internet Explorer * * Additional configuration params can be used from [IE options](https://seleniumhq.github.io/selenium/docs/api/rb/Selenium/WebDriver/IE/Options.html) * * ```js * { * helpers: { * WebDriver : { * url: "http://localhost", * browser: "internet explorer", * desiredCapabilities: { * ieOptions: { * "ie.browserCommandLineSwitches": "-private", * "ie.usePerProcessProxy": true, * "ie.ensureCleanSession": true, * } * } * } * } * } * ``` * * ### Selenoid Options * * [Selenoid](https://aerokube.com/selenoid/latest/) is a modern way to run Selenium inside Docker containers. * Selenoid is easy to set up and provides more features than original Selenium Server. Use `selenoidOptions` to set Selenoid capabilities * * ```js * { * helpers: { * WebDriver : { * url: "http://localhost", * browser: "chrome", * desiredCapabilities: { * selenoidOptions: { * enableVNC: true, * } * } * } * } * } * ``` * * ### Connect Through proxy * * CodeceptJS also provides flexible options when you want to execute tests to Selenium servers through proxy. You will * need to update the `helpers.WebDriver.capabilities.proxy` key. * * ```js * { * helpers: { * WebDriver: { * capabilities: { * proxy: { * "proxyType": "manual|pac", * "proxyAutoconfigUrl": "URL TO PAC FILE", * "httpProxy": "PROXY SERVER", * "sslProxy": "PROXY SERVER", * "ftpProxy": "PROXY SERVER", * "socksProxy": "PROXY SERVER", * "socksUsername": "USERNAME", * "socksPassword": "PASSWORD", * "noProxy": "BYPASS ADDRESSES" * } * } * } * } * } * ``` * For example, * * ```js * { * helpers: { * WebDriver: { * capabilities: { * proxy: { * "proxyType": "manual", * "httpProxy": "http://corporate.proxy:8080", * "socksUsername": "codeceptjs", * "socksPassword": "secret", * "noProxy": "127.0.0.1,localhost" * } * } * } * } * } * ``` * * Please refer to [Selenium - Proxy Object](https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities) for more * information. * * ### Cloud Providers * * WebDriver makes it possible to execute tests against services like `Sauce Labs` `BrowserStack` `TestingBot` * Check out their documentation on [available parameters](http://webdriver.io/guide/usage/cloudservices.html) * * Connecting to `BrowserStack` and `Sauce Labs` is simple. All you need to do * is set the `user` and `key` parameters. WebDriver automatically know which * service provider to connect to. * * ```js * { * helpers:{ * WebDriver: { * url: "YOUR_DESIRED_HOST", * user: "YOUR_BROWSERSTACK_USER", * key: "YOUR_BROWSERSTACK_KEY", * capabilities: { * "browserName": "chrome", * * // only set this if you're using BrowserStackLocal to test a local domain * // "browserstack.local": true, * * // set this option to tell browserstack to provide addition debugging info * // "browserstack.debug": true, * } * } * } * } * ``` * * #### SauceLabs * * SauceLabs can be configured via wdio service, which should be installed additionally: * * ``` * npm i @wdio/sauce-service --save * ``` * * It is important to make sure it is compatible with current webdriverio version. * * Enable `wdio` plugin in plugins list and add `sauce` service: * * ```js * plugins: { * wdio: { * enabled: true, * services: ['sauce'], * user: ... ,// saucelabs username * key: ... // saucelabs api key * // additional config, from sauce service * } * } * ``` * * See [complete reference on webdriver.io](https://webdriver.io/docs/sauce-service.html). * * > Alternatively, use [codeceptjs-saucehelper](https://github.com/puneet0191/codeceptjs-saucehelper/) for better reporting. * * #### BrowserStack * * BrowserStack can be configured via wdio service, which should be installed additionally: * * ``` * npm i @wdio/browserstack-service --save * ``` * * It is important to make sure it is compatible with current webdriverio version. * * Enable `wdio` plugin in plugins list and add `browserstack` service: * * ```js * plugins: { * wdio: { * enabled: true, * services: ['browserstack'], * user: ... ,// browserstack username * key: ... // browserstack api key * // additional config, from browserstack service * } * } * ``` * * See [complete reference on webdriver.io](https://webdriver.io/docs/browserstack-service.html). * * > Alternatively, use [codeceptjs-bshelper](https://github.com/PeterNgTr/codeceptjs-bshelper) for better reporting. * * #### TestingBot * * > **Recommended**: use official [TestingBot Helper](https://github.com/testingbot/codeceptjs-tbhelper). * * Alternatively, TestingBot can be configured via wdio service, which should be installed additionally: * * ``` * npm i @wdio/testingbot-service --save * ``` * * It is important to make sure it is compatible with current webdriverio version. * * Enable `wdio` plugin in plugins list and add `testingbot` service: * * ```js * plugins: { * wdio: { * enabled: true, * services: ['testingbot'], * user: ... ,// testingbot key * key: ... // testingbot secret * // additional config, from testingbot service * } * } * ``` * * See [complete reference on webdriver.io](https://webdriver.io/docs/testingbot-service.html). * * #### Applitools * * Visual testing via Applitools service * * > Use [CodeceptJS Applitools Helper](https://github.com/PeterNgTr/codeceptjs-applitoolshelper) with Applitools wdio service. * * * ### Multiremote Capabilities * * This is a work in progress but you can control two browsers at a time right out of the box. * Individual control is something that is planned for a later version. * * Here is the [webdriverio docs](http://webdriver.io/guide/usage/multiremote.html) on the subject * * ```js * { * helpers: { * WebDriver: { * "multiremote": { * "MyChrome": { * "desiredCapabilities": { * "browserName": "chrome" * } * }, * "MyFirefox": { * "desiredCapabilities": { * "browserName": "firefox" * } * } * } * } * } * } * ``` * * ## Access From Helpers * * Receive a WebDriver client from a custom helper by accessing `browser` property: * * ```js * const { WebDriver } = this.helpers; * const browser = WebDriver.browser * ``` * * ## Methods */ class WebDriver extends Helper { constructor(config) { super(config); webdriverio = requireg('webdriverio'); if (webdriverio.VERSION && webdriverio.VERSION.indexOf('4') === 0) { throw new Error(`This helper is compatible with "webdriverio@5". Current version: ${webdriverio.VERSION}. Please upgrade webdriverio to v5+ or use WebDriverIO helper instead`); } // set defaults this.root = webRoot; this.isWeb = true; this.isRunning = false; this._setConfig(config); Locator.addFilter((locator, result) => { if (typeof locator === 'string' && locator.indexOf('~') === 0) { // accessibility locator if (this.isWeb) { result.value = `[aria-label="${locator.slice(1)}"]`; result.type = 'css'; result.output = `aria-label=${locator.slice(1)}`; } } }); } _validateConfig(config) { const defaults = { logLevel: 'silent', // codeceptjs remoteFileUpload: true, smartWait: 0, waitForTimeout: 1000, // ms capabilities: {}, restart: true, uniqueScreenshotNames: false, disableScreenshots: false, fullPageScreenshots: false, manualStart: false, keepCookies: false, keepBrowserState: false, deprecationWarnings: false, timeouts: { script: 1000, // ms }, }; // override defaults with config config = Object.assign(defaults, config); if (typeof config.host !== 'undefined') config.hostname = config.host; // webdriverio spec config.baseUrl = config.url || config.baseUrl; if (config.desiredCapabilities && Object.keys(config.desiredCapabilities).length) { config.capabilities = config.desiredCapabilities; } config.capabilities.browserName = config.browser || config.capabilities.browserName; if (config.capabilities.chromeOptions) { config.capabilities['goog:chromeOptions'] = config.capabilities.chromeOptions; delete config.capabilities.chromeOptions; } if (config.capabilities.firefoxOptions) { config.capabilities['moz:firefoxOptions'] = config.capabilities.firefoxOptions; delete config.capabilities.firefoxOptions; } if (config.capabilities.ieOptions) { config.capabilities['se:ieOptions'] = config.capabilities.ieOptions; delete config.capabilities.ieOptions; } if (config.capabilities.selenoidOptions) { config.capabilities['selenoid:options'] = config.capabilities.selenoidOptions; delete config.capabilities.selenoidOptions; } config.waitForTimeout /= 1000; // convert to seconds if (!config.capabilities.platformName && (!config.url || !config.browser)) { throw new Error(` WebDriver requires at url and browser to be set. Check your codeceptjs config file to ensure these are set properly { "helpers": { "WebDriver": { "url": "YOUR_HOST" "browser": "YOUR_PREFERRED_TESTING_BROWSER" } } } `); } return config; } static _checkRequirements() { try { requireg('webdriverio'); } catch (e) { return ['webdriverio@^5.2.2']; } } static _config() { return [{ name: 'url', message: 'Base url of site to be tested', default: 'http://localhost', }, { name: 'browser', message: 'Browser in which testing will be performed', default: 'chrome', }]; } _beforeSuite() { if (!this.options.restart && !this.options.manualStart && !this.isRunning) { this.debugSection('Session', 'Starting singleton browser session'); return this._startBrowser(); } } async _startBrowser() { try { if (this.options.multiremote) { this.browser = await webdriverio.multiremote(this.options.multiremote); } else { this.browser = await webdriverio.remote(this.options); } } catch (err) { if (err.toString().indexOf('ECONNREFUSED')) { throw new ConnectionRefused(err); } throw err; } this.isRunning = true; if (this.options.timeouts && this.isWeb) { await this.defineTimeout(this.options.timeouts); } await this._resizeWindowIfNeeded(this.browser, this.options.windowSize); this.$$ = this.browser.$$.bind(this.browser); return this.browser; } async _stopBrowser() { if (this.browser && this.isRunning) await this.browser.deleteSession(); } async _before() { this.context = this.root; if (this.options.restart && !this.options.manualStart) return this._startBrowser(); if (!this.isRunning && !this.options.manualStart) return this._startBrowser(); this.$$ = this.browser.$$.bind(this.browser); return this.browser; } async _after() { if (!this.isRunning) return; if (this.options.restart) { this.isRunning = false; return this.browser.deleteSession(); } if (this.browser.isInsideFrame) await this.browser.switchToFrame(null); if (this.options.keepBrowserState) return; if (!this.options.keepCookies && this.options.capabilities.browserName) { this.debugSection('Session', 'cleaning cookies and localStorage'); await this.browser.deleteCookies(); } await this.browser.execute('localStorage.clear();').catch((err) => { if (!(err.message.indexOf("Storage is disabled inside 'data:' URLs.") > -1)) throw err; }); await this.closeOtherTabs(); return this.browser; } _afterSuite() { } _finishTest() { if (!this.options.restart && this.isRunning) return this._stopBrowser(); } _session() { const defaultSession = this.browser; return { start: async (opts) => { // opts.disableScreenshots = true; // screenshots cant be saved as session will be already closed opts = this._validateConfig(Object.assign(this.options, opts)); this.debugSection('New Browser', JSON.stringify(opts)); const browser = await webdriverio.remote(opts); if (opts.timeouts && this.isWeb) { await this._defineBrowserTimeout(browser, opts.timeouts); } await this._resizeWindowIfNeeded(browser, opts.windowSize); return browser; }, stop: async (browser) => { return browser.deleteSession(); }, loadVars: async (browser) => { if (this.context !== this.root) throw new Error('Can\'t start session inside within block'); this.browser = browser; this.$$ = this.browser.$$.bind(this.browser); }, restoreVars: async () => { this.browser = defaultSession; this.$$ = this.browser.$$.bind(this.browser); }, }; } async _failed(test) { if (this.context !== this.root) await this._withinEnd(); } async _withinBegin(locator) { const frame = isFrameLocator(locator); if (frame) { this.browser.isInsideFrame = true; if (Array.isArray(frame)) { // this.switchTo(null); await forEachAsync(frame, async f => this.switchTo(f)); return; } await this.switchTo(frame); return; } this.context = locator; let res = await this.browser.$$(withStrictLocator(locator)); assertElementExists(res, locator); res = usingFirstElement(res); this.context = res.selector; this.$$ = res.$$.bind(res); } async _withinEnd() { if (this.browser.isInsideFrame) { this.browser.isInsideFrame = false; return this.switchTo(null); } this.context = this.root; this.$$ = this.browser.$$.bind(this.browser); } /** * Get elements by different locator types, including strict locator. * Should be used in custom helpers: * * ```js * this.helpers['WebDriver']._locate({name: 'password'}).then //... * ``` * * * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator. */ async _locate(locator, smartWait = false) { if (require('../store').debugMode) smartWait = false; // special locator type for React if (locator.react) { const els = await this.browser.react$$(locator.react, locator.props || undefined, locator.state || undefined); this.debugSection('Elements', `Found ${els.length} react components`); return els; } if (!this.options.smartWait || !smartWait) { const els = await this.$$(withStrictLocator(locator)); return els; } this.debugSection(`SmartWait (${this.options.smartWait}ms)`, `Locating ${locator} in ${this.options.smartWait}`); await this.defineTimeout({ implicit: this.options.smartWait }); const els = await this.$$(withStrictLocator(locator)); await this.defineTimeout({ implicit: 0 }); return els; } /** * Find a checkbox by providing human readable text: * * ```js * this.helpers['WebDriver']._locateCheckable('I agree with terms and conditions').then // ... * ``` * * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator. */ async _locateCheckable(locator) { return findCheckable.call(this, locator, this.$$.bind(this)).then(res => res); } /** * Find a clickable element by providing human readable text: * * ```js * this.helpers['WebDriver']._locateClickable('Next page').then // ... * ``` * * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator. */ async _locateClickable(locator) { return findClickable.call(this, locator, this.$$.bind(this)).then(res => res); } /** * Find field elements by providing human readable text: * * ```js * this.helpers['WebDriver']._locateFields('Your email').then // ... * ``` * * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator. */ async _locateFields(locator) { return findFields.call(this, locator).then(res => res); } /** * Set [WebDriver timeouts](https://webdriver.io/docs/timeouts.html) in realtime. * * Timeouts are expected to be passed as object: * * ```js * I.defineTimeout({ script: 5000 }); * I.defineTimeout({ implicit: 10000, pageLoad: 10000, script: 5000 }); * ``` * * @param {WebdriverIO.Timeouts} timeouts WebDriver timeouts object. */ defineTimeout(timeouts) { return this._defineBrowserTimeout(this.browser, timeouts); } _defineBrowserTimeout(browser, timeouts) { return browser.setTimeout(timeouts); } /** * * Opens a web page in a browser. Requires relative or absolute url. If url starts with `/`, opens a web page of a site defined in `url` config parameter. ```js I.amOnPage('/'); // opens main page of website I.amOnPage('https://github.com'); // opens github I.amOnPage('/login'); // opens a login page ``` @param {string} url url path or global url. * */ amOnPage(url) { return this.browser.url(url); } /** * * Perform a click on a link or a button, given by a locator. If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the "value" attribute, "name" attribute, and inner text are searched. For links, the link text is searched. For images, the "alt" attribute and inner text of any parent links are searched. The second parameter is a context (CSS or XPath locator) to narrow the search. ```js // simple link I.click('Logout'); // button of form I.click('Submit'); // CSS button I.click('#form input[type=submit]'); // XPath I.click('//form/*[@type=submit]'); // link in context I.click('Logout', '#nav'); // using strict locator I.click({css: 'nav a.login'}); ``` @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator. @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator. * * {{ react }} */ async click(locator, context = null) { const clickMethod = this.browser.isMobile ? 'touchClick' : 'elementClick'; const locateFn = prepareLocateFn.call(this, context); const res = await findClickable.call(this, locator, locateFn); if (context) { assertElementExists(res, locator, 'Clickable element', `was not found inside element ${new Locator(context)}`); } else { assertElementExists(res, locator, 'Clickable element'); } const elem = usingFirstElement(res); return this.browser[clickMethod](getElementId(elem)); } /** * * Performs a double-click on an element matched by link|button|label|CSS or XPath. Context can be specified as second parameter to narrow search. ```js I.doubleClick('Edit'); I.doubleClick('Edit', '.actions'); I.doubleClick({css: 'button.accept'}); I.doubleClick('.btn.edit'); ``` @param {CodeceptJS.LocatorOrString} locator clickable link or button located by text, or any element located by CSS|XPath|strict locator. @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element to search in CSS|XPath|Strict locator. * * {{ react }} */ async doubleClick(locator, context = null) { const locateFn = prepareLocateFn.call(this, context); const res = await findClickable.call(this, locator, locateFn); if (context) { assertElementExists(res, locator, 'Clickable element', `was not found inside element ${new Locator(context)}`); } else { assertElementExists(res, locator, 'Clickable element'); } const elem = usingFirstElement(res); return elem.doubleClick(); } /** * * Performs right click on a clickable element matched by semantic locator, CSS or XPath. ```js // right click element with id el I.rightClick('#el'); // right click link or button with text "Click me" I.rightClick('Click me'); // right click button with text "Click me" inside .context I.rightClick('Click me', '.context'); ``` @param {CodeceptJS.LocatorOrString} locator clickable element located by CSS|XPath|strict locator. @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS|XPath|strict locator. * * {{ react }} */ async rightClick(locator, context) { const locateFn = prepareLocateFn.call(this, context); const res = await findClickable.call(this, locator, locateFn); if (context) { assertElementExists(res, locator, 'Clickable element', `was not found inside element ${new Locator(context)}`); } else { assertElementExists(res, locator, 'Clickable element'); } const el = usingFirstElement(res); await el.moveTo(); if (this.browser.isW3C) { // W3C version return this.browser.performActions([ { type: 'pointerDown', button: 2 }, ]); } // JSON Wire version await this.browser.buttonDown(2); } /** * * Fills a text field or textarea, after clearing its value, with the given string. Field is located by name, label, CSS, or XPath. ```js // by label I.fillField('Email', 'hello@world.com'); // by name I.fillField('password', secret('123456')); // by CSS I.fillField('form#login input[name=username]', 'John'); // or by strict locator I.fillField({css: 'form#login input[name=username]'}, 'John'); ``` @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator. @param {string} value text value to fill. * {{ react }} * */ async fillField(field, value) { const res = await findFields.call(this, field); assertElementExists(res, field, 'Field'); const elem = usingFirstElement(res); return elem.setValue(value.toString()); } /** * * Appends text to a input field or textarea. Field is located by name, label, CSS or XPath ```js I.appendField('#myTextField', 'appended'); ``` @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator @param {string} value text value to append. * {{ react }} */ async appendField(field, value) { const res = await findFields.call(this, field); assertElementExists(res, field, 'Field'); const elem = usingFirstElement(res); return elem.addValue(value); } /** * * Clears a `<textarea>` or text `<input>` element's value. ```js I.clearField('Email'); I.clearField('user[email]'); I.clearField('#email'); ``` @param {string|object} editable field located by label|name|CSS|XPath|strict locator. * */ async clearField(field) { const res = await findFields.call(this, field); assertElementExists(res, field, 'Field'); const elem = usingFirstElement(res); return elem.clearValue(getElementId(elem)); } /** * * Selects an option in a drop-down select. Field is searched by label | name | CSS | XPath. Option is selected by visible text or by value. ```js I.selectOption('Choose Plan', 'Monthly'); // select by label I.selectOption('subscription', 'Monthly'); // match option by text I.selectOption('subscription', '0'); // or by value I.selectOption('//form/select[@name=account]','Premium'); I.selectOption('form select[name=account]', 'Premium'); I.selectOption({css: 'form select[name=account]'}, 'Premium'); ``` Provide an array for the second argument to select multiple options. ```js I.selectOption('Which OS do you use?', ['Android', 'iOS']); ``` @param {CodeceptJS.LocatorOrString} select field located by label|name|CSS|XPath|strict locator. @param {string|Array<*>} option visible text or value of option. */ async selectOption(select, option) { const res = await findFields.call(this, select); assertElementExists(res, select, 'Selectable field'); const elem = usingFirstElement(res); if (!Array.isArray(option)) { option = [option]; } // select options by visible text let els = await forEachAsync(option, async opt => this.browser.findElementsFromElement(getElementId(elem), 'xpath', Locator.select.byVisibleText(xpathLocator.literal(opt)))); const clickOptionFn = async (el) => { if (el[0]) el = el[0]; const elementId = getElementId(el); if (elementId) return this.browser.elementClick(elementId); }; if (Array.isArray(els) && els.length) { return forEachAsync(els, clickOptionFn); } // select options by value els = await forEachAsync(option, async opt => this.browser.findElementsFromElement(getElementId(elem), 'xpath', Locator.select.byValue(xpathLocator.literal(opt)))); if (els.length === 0) { throw new ElementNotFound(select, `Option "${option}" in`, 'was not found neither by a visible text nor by a value'); } return forEachAsync(els, clickOptionFn); } /** * * Attaches a file to element located by label, name, CSS or XPath Path to file is relative current codecept directory (where codecept.json or codecept.conf.js is located). File will be uploaded to remote system (if tests are running remotely). ```js I.attachFile('Avatar', 'data/avatar.jpg'); I.attachFile('form input[name=avatar]', 'data/avatar.jpg'); ``` @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator. @param {string} pathToFile local file path relative to codecept.json config file. * Appium: not tested */ async attachFile(locator, pathToFile) { let file = path.join(global.codecept_dir, pathToFile); if (!fileExists(file)) { throw new Error(`File at ${file} can not be found on local system`); } const res = await findFields.call(this, locator); this.debug(`Uploading ${file}`); assertElementExists(res, locator, 'File field'); const el = usingFirstElement(res); // Remote Upload (when running Selenium Server) if (this.options.remoteFileUpload) { try { this.debugSection('File', 'Uploading file to remote server'); file = await this.browser.uploadFile(file); } catch (err) { throw new Error(`File can't be transferred to remote server. Set \`remoteFileUpload: false\` in config to upload file locally.\n${err.message}`); } } return el.addValue(file); } /** * * Selects a checkbox or radio button. Element is located by label or name or CSS or XPath. The second parameter is a context (CSS or XPath locator) to narrow the search. ```js I.checkOption('#agree'); I.checkOption('I Agree to Terms and Conditions'); I.checkOption('agree', '//form'); ``` @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator. @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator. * Appium: not tested */ async checkOption(field, context = null) { const clickMethod = this.browser.isMobile ? 'touchClick' : 'elementClick'; const locateFn = prepareLocateFn.call(this, context); const res = await findCheckable.call(this, field, locateFn); assertElementExists(res, field, 'Checkable'); const elem = usingFirstElement(res); const elementId = getElementId(elem); const isSelected = await this.browser.isElementSelected(elementId); if (isSelected) return Promise.resolve(true); return this.browser[clickMethod](elementId); } /** * * Unselects a checkbox or radio button. Element is located by label or name or CSS or XPath. The second parameter is a context (CSS or XPath locator) to narrow the search. ```js I.uncheckOption('#agree'); I.uncheckOption('I Agree to Terms and Conditions'); I.uncheckOption('agree', '//form'); ``` @param {CodeceptJS.LocatorOrString} field checkbox located by label | name | CSS | XPath | strict locator. @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS | XPath | strict locator. * Appium: not tested */ async uncheckOption(field, context = null) { const clickMethod = this.browser.isMobile ? 'touchClick' : 'elementClick'; const locateFn = prepareLocateFn.call(this, context); const res = await findCheckable.call(this, field, locateFn); assertElementExists(res, field, 'Checkable'); const elem = usingFirstElement(res); const elementId = getElementId(elem); const isSelected = await this.browser.isElementSelected(elementId); if (!isSelected) return Promise.resolve(true); return this.browser[clickMethod](elementId); } /** * * Retrieves a text from an element located by CSS or XPath and returns it to test. Resumes test execution, so **should be used inside async with `await`** operator. ```js let pin = await I.grabTextFrom('#pin'); ``` If multiple elements found returns an array of texts. @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator. @returns {Promise<string|string[]>} attribute value * */ async grabTextFrom(locator) { const res = await this._locate(locator, true); assertElementExists(res, locator); let val; if (res.length > 1) { val = await forEachAsync(res, async el => this.browser.getElementText(getElementId(el))); } else { val = await this.browser.getElementText(getElementId(res[0])); } this.debugSection('Grab', val); return val; } /** * * Retrieves the innerHTML from an element located by CSS or XPath and returns it to test. Resumes test execution, so **should be used inside async function with `await`** operator. If more than one element is found - an array of HTMLs returned. ```js let postHTML = await I.grabHTMLFrom('#post'); ``` @param {CodeceptJS.LocatorOrString} element located by CSS|XPath|strict locator. @returns {Promise<string>} HTML code for an element * */ async grabHTMLFrom(locator) { const elems = await this._locate(locator, true); assertElementExists(elems, locator); const values = await Promise.all(elems.map(elem => elem.getHTML(false))); this.debugSection('Grab', values); if (Array.isArray(values) && values.length === 1) { return values[0]; } return values; } /** * * Retrieves a value from a form element located by CSS or XPath and returns it to test. Resumes test execution, so **should be used inside async function with `await`** operator. ```js let email = await I.grabValueFrom('input[name=email]'); ``` @param {CodeceptJS.LocatorOrString} locator field located by label|name|CSS|XPath|strict locator. @returns {Promise<string>} attribute value * */ async grabValueFrom(locator) { const res = await this._locate(locator, true); assertElementExists(res, locator); return forEachAsync(res, async el => el.getValue()); } /** * * Grab CSS property for given locator Resumes test execution, so **should be used inside an async function with `await`** operator. ```js const value = await I.grabCssPropertyFrom('h3', 'font-weight'); ``` @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator. @param {string} cssProperty CSS property name. @returns {Promise<string>} CSS value */ async grabCssPropertyFrom(locator, cssProperty) { const res = await this._locate(locator, true); assertElementExists(res, locator); return forEachAsync(res, async el => this.browser.getElementCSSValue(getElementId(el), cssProperty)); } /** * * Retrieves an attribute from an element located by CSS or XPath and returns it to test. An array as a result will be returned if there are more than one matched element. Resumes test execution, so **should be used inside async with `await`** operator. ```js let hint = await I.grabAttributeFrom('#tooltip', 'title'); ``` @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator. @param {string} attr attribute name. @returns {Promise<string>} attribute value * Appium: can be used for apps only with several values ("contentDescription", "text", "className", "resourceId") */ async grabAttributeFrom(locator, attr) { const res = await this._locate(locator, true); assertElementExists(res, locator); return forEachAsync(res, async el => el.getAttribute(attr)); } /** * * Checks that title contains text. ```js I.seeInTitle('Home Page'); ``` @param {string} text text value to check. * */ async seeInTitle(text) { const title = await this.browser.getTitle(); return stringIncludes('web page title').assert(text, title); } /** * Checks that title is equal to provided one. * * ```js * I.seeTitleEquals('Test title.'); * ``` * * @param {string} text value to check. */ async seeTitleEquals(text) { const title = await this.browser.getTitle(); return assert.equal(title, text, `expected web page title to be ${text}, but found ${title}`); } /** * * Checks that title does not contain text. ```js I.dontSeeInTitle('Error'); ``` @param {string} text value to check. * */ async dontSeeInTitle(text) { const title = await this.browser.getTitle(); return stringIncludes('web page title').negate(text, title); } /** * * Retrieves a page title and returns it to test. Resumes test execution, so **should be used inside async with `await`** operator. ```js let title = await I.grabTitle(); ``` @returns {Promise<string>} title * */ async grabTitle() { const title = await this.browser.getTitle(); this.debugSection('Title', title); return title; } /** * * Checks that a page contains a visible text. Use context parameter to narrow down the search. ```js I.see('Welcome'); // text welcome on a page I.see('Welcome', '.content'); // text inside .content div I.see('Register', {css: 'form.register'}); // use strict locator ``` @param {string} text expected on page. @param {?CodeceptJS.LocatorOrString} [context=null] (optional, `null` by default) element located by CSS|Xpath|strict locator in which to search for text. * * {{ react }} */ async see(text, context = null) { return proceedSee.call(this, 'assert', text, context); } /** * Checks that text is equal to provided one. * * ```js * I.seeTextEquals('text', 'h1'); * ``` * * @param {string} text element value to check. * @param {CodeceptJS.LocatorOrString?} [context] (optional) element located by CSS|XPath|strict locator. */ async seeTextEquals(text, context = null) { return proceedSee.call(this, 'assert', text, context, true); } /** * * Opposite to `see`. Checks that a text is not present on a page. Use context parameter to narrow down the search. ```js I.dontSee('Login'); // assume we are already logged in. I.dontSee('Login', '.nav'); // no login inside .nav element ``` @param {string} text which is not present. @param {CodeceptJS.LocatorOrString} [context] (optional) element located by CSS|XPath|strict locator in which to perfrom search. * * {{ react }} */ async dontSee(text, context = null) { return proceedSee.call(this, 'negate', text, context); } /** * * Checks that the given input field or textarea equals to given value. For fuzzy locators, fields are matched by label text, the "name" attribute, CSS, and XPath. ```js I.seeInField('Username', 'davert'); I.seeInField({css: 'form textarea'},'Type your comment here'); I.seeInField('form input[type=hidden]','hidden_value'); I.seeInField('#searchform input','Search'); ``` @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator. @param {string} value value to check. * */ async seeInField(field, value) { return proceedSeeField.call(this, 'assert', field, value); } /** * * Checks that value of input field or textarea doesn't equal to given value Opposite to `seeInField`. ```js I.dontSeeInField('email', 'user@user.com'); // field by name I.dontSeeInField({ css: 'form input.email' }, 'user@user.com'); // field by CSS ``` @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator. @param {string} value value to check. * */ async dontSeeInField(field, value) { return proceedSeeField.call(this, 'negate', field, value); } /** * * Verifies that the specified checkbox is checked. ```js I.seeCheckboxIsChecked('Agree'); I.seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms I.seeCheckboxIsChecked({css: '#signup_form input[type=checkbox]'}); ``` @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator. * Appium: not tested */ async seeCheckboxIsChecked(field) { return proceedSeeCheckbox.call(this, 'assert', field); } /** * * Verifies that the specified checkbox is not checked. ```js I.dontSeeCheckboxIsChecked('#agree'); // located by ID I.dontSeeCheckboxIsChecked('I agree to terms'); // located by label I.dontSeeCheckboxIsChecked('agree'); // located by name ``` @param {CodeceptJS.LocatorOrString} field located by label|name|CSS|XPath|strict locator. * Appium: not tested */ async dontSeeCheckboxIsChecked(field) { return proceedSeeCheckbox.call(this, 'negate', field); } /** * * Checks that a given Element is visible Element is located by CSS or XPath. ```js I.seeElement('#modal'); ``` @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator. * {{ react }} * */ async seeElement(locator) { const res = await this._locate(locator, true); assertElementExists(res, locator); const selected = await forEachAsync(res, async el => el.isDisplayed()); return truth(`elements of ${locator}`, 'to be seen').assert(selected); } /** * * Opposite to `seeElement`. Checks that element is not visible (or in DOM) ```js I.dontSeeElement('.modal'); // modal is not shown ``` @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator. * {{ react }} */ async dontSeeElement(locator) { const res = await this._locate(locator, false); if (!res || res.length === 0) { return truth(`elements of ${locator}`, 'to be seen').negate(false); } const selected = await forEachAsync(res, async el => el.isDisplayed()); return truth(`elements of ${locator}`, 'to be seen').negate(selected); } /** * * Checks that a given Element is present in the DOM Element is located by CSS or XPath. ```js I.seeElementInDOM('#modal'); ``` @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator. * */ async seeElementInDOM(locator) { const res = await this.$$(withStrictLocator(locator)); return empty('elements').negate(res); } /** * * Opposite to `seeElementInDOM`. Checks that element is not on page. ```js I.dontSeeElementInDOM('.nav'); // checks that element is not on page visible or not ``` @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|Strict locator. * */ async dontSeeElementInDOM(locator) { const res = await this.$$(withStrictLocator(locator)); return empty('elements').assert(res); } /** * * Checks that the current page contains the given string in its raw source code. ```js I.seeInSource('<h1>Green eggs &amp; ham</h1>'); ``` @param {string} text value to check. * */ async seeInSource(text) { const source = await this.browser.getPageSource(); return stringIncludes('HTML source of a page').assert(text, source); } /** * * Retrieves page source and returns it to test. Resumes test execution, so should be used inside an async function. ```js let pageSource = await I.grabSource(); ``` @returns {Promise<string>} source code * */ async grabSource() { return this.browser.getPageSource(); } /** * Get JS log from browser. Log buffer is reset after each request. * * ```js * let logs = await I.grabBrowserLogs(); * console.log(JSON.stringify(logs)) * ``` * @returns {Promise<string|undefined>} */ async grabBrowserLogs() { if (this.browser.isW3C) { this.debug('Logs not awailable in W3C specification'); return; } return this.browser.getLogs('browser'); } /** * * Get current URL from browser. Resumes test execution, so should be used inside an async function. ```js let url = await I.grabCurrentUrl(); console.log(`Current URL is [${url}]`); ``` @returns {Promise<string>} current URL */ async grabCurrentUrl() { const res = await this.browser.getUrl(); this.debugSection('Url', res); return res; } /** * * Checks that the current page does not contains the given string in its raw source code. ```js I.dontSeeInSource('<!--'); // no comments in source ``` @param {string} value to check. */ async dontSeeInSource(text) { const source = await this.browser.getPageSource(); return stringIncludes('HTML source of a page').negate(text, source); } /** * * Asserts that an element appears a given number of times in the DOM. Element is located by label or name or CSS or XPath. ```js I.seeNumberOfElements('#submitBtn', 1); ``` @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator. @param {number} num number of elements. * {{ react }} */ async seeNumberOfElements(locator, num) { const res = await this._locate(locator); return assert.equal(res.length, num, `expected number of elements (${locator}) is ${num}, but found ${res.length}`); } /** * * Asserts that an element is visible a given number of times. Element is located by CSS or XPath. ```js I.seeNumberOfVisibleElements('.buttons', 3); ``` @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator. @param {number} num number of elements. * {{ react }} */ async seeNumberOfVisibleElements(locator, num) { const res = await this.grabNumberOfVisibleElements(locator); return assert.equal(res, num, `expected number of visible elements (${locator}) is ${num}, but found ${res}`); } /** * * Checks that all elements with given locator have given CSS properties. ```js I.seeCssPropertiesOnElements('h3', { 'font-weight': "bold"}); ``` @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator. @param {object} cssProperties object with CSS properties and their values to check. */ async seeCssPropertiesOnElements(locator, cssProperties) { const res = await this._locate(locator); assertElementExists(res, locator); const elemAmount = res.length; let props = await forEachAsync(res, async (el) => { return forEachAsync(Object.keys(cssProperties), async (prop) => { const propValue = await this.browser.getElementCSSValue(getElementId(el), prop); if (isColorProperty(prop) && propValue && propValue.value) { return convertColorToRGBA(propValue.value); } return propValue; }); }); const cssPropertiesCamelCase = convertCssPropertiesToCamelCase(cssProperties); const values = Object.keys(cssPropertiesCamelCase).map(key => cssPropertiesCamelCase[key]); if (!Array.isArray(props)) props = [props]; let chunked = chunkArray(props, values.length); chunked = chunked.filter((val) => { for (let i = 0; i < val.length; ++i) { if (val[i] !== values[i]) return false; } return true; }); return assert.ok( chunked.length === elemAmount, `expected all elements (${locator}) to have CSS property ${JSON.stringify(cssProperties)}`, ); } /** * * Checks that all elements with given locator have given attributes. ```js I.seeAttributesOnElements('//form', { method: "post"}); ``` @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator. @param {object} attributes attributes and their values to check. */ async seeAttributesOnElements(locator, attributes) { const res = await this._locate(locator); assertElementExists(res, locator); const elemAmount = res.length; let attrs = await forEachAsync(res, async (el) => { return forEachAsync(Object.keys(attributes), async attr => el.getAttribute(attr)); }); const values = Object.keys(attributes).map(key => attributes[key]); if (!Array.isArray(attrs)) attrs = [attrs]; let chunked = chunkArray(attrs, values.length); chunked = chunked.filter((val) => { for (let i = 0; i < val.length; ++i) { if (val[i] !== values[i]) return false; } return true; }); return assert.ok( chunked.length === elemAmount, `expected all elements (${locator}) to have attributes ${JSON.stringify(attributes)}`, ); } /** * * Grab number of visible ele