UNPKG

codeceptjs

Version:

Modern Era Acceptance Testing Framework for NodeJS

1,582 lines (1,378 loc) 88.5 kB
let webdriverio; const requireg = require('requireg'); const Helper = require('../helper'); const stringIncludes = require('../assert/include').includes; const { urlEquals, equals } = require('../assert/equal'); const empty = require('../assert/empty').empty; const truth = require('../assert/truth').truth; const { xpathLocator, fileExists, clearString, decodeUrl, chunkArray, convertCssPropertiesToCamelCase, screenshotOutputFolder, } = require('../utils'); const { isColorProperty, convertColorToRGBA, } = require('../colorUtils'); const ElementNotFound = require('./errors/ElementNotFound'); const ConnectionRefused = require('./errors/ConnectionRefused'); const assert = require('assert'); const path = require('path'); const webRoot = 'body'; const Locator = require('../locator'); let withinStore = {}; /** * WebDriverIO helper which wraps [webdriverio](http://webdriver.io/) library to * manipulate browser using Selenium WebDriver or PhantomJS. * * WebDriverIO 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["WebDriverIO"]._startBrowser()`. * * `timeouts`: [WebDriverIO timeouts](http://webdriver.io/guide/testrunner/timeouts.html) defined as hash. * * Example: * * ```json * { * "helpers": { * "WebDriverIO" : { * "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 * * ```json * { * "helpers": { * "WebDriverIO" : { * "url": "http://localhost", * "browser": "chrome", * "desiredCapabilities": { * "chromeOptions": { * "args": [ "--headless", "--disable-gpu", "--no-sandbox" ] * } * } * } * } * } * ``` * * ### 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.WebDriverIO.desiredCapabilities.proxy` key. * * ```js * { * "helpers": { * "WebDriverIO": { * "desiredCapabilities": { * "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": { * "WebDriverIO": { * "desiredCapabilities": { * "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 * * WebDriverIO 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. WebDriverIO automatically know which * service provider to connect to. * * ```js * { * "helpers":{ * "WebDriverIO": { * "url": "YOUR_DESIRED_HOST", * "user": "YOUR_BROWSERSTACK_USER", * "key": "YOUR_BROWSERSTACK_KEY", * "desiredCapabilities": { * "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, * } * } * } * } * ``` * * ### 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": { * "WebDriverIO": { * "multiremote": { * "MyChrome": { * "desiredCapabilities": { * "browserName": "chrome" * } * }, * "MyFirefox": { * "desiredCapabilities": { * "browserName": "firefox" * } * } * } * } * } * } * ``` * * * ## Access From Helpers * * Receive a WebDriverIO client from a custom helper by accessing `browser` property: * * ```js * this.helpers['WebDriverIO'].browser * ``` */ class WebDriverIO extends Helper { constructor(config) { super(config); webdriverio = requireg('webdriverio'); console.log('DEPRECATION WARNING', 'WebDriverIO helper is deprecated'); console.log('DEPRECATION WARNING', 'WebDriverIO was based on webdriverio package v4 which is outdated now'); console.log('DEPRECATION WARNING', 'Upgrade to "webdriverio@5" and switch to WebDriver helper'); // set defaults this.root = webRoot; this.isRunning = false; this._setConfig(config); } _validateConfig(config) { const defaults = { smartWait: 0, waitForTimeout: 1000, // ms desiredCapabilities: {}, 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); config.baseUrl = config.url || config.baseUrl; config.desiredCapabilities.browserName = config.browser || config.desiredCapabilities.browserName; config.waitForTimeout /= 1000; // convert to seconds if (!config.desiredCapabilities.platformName && (!config.url || !config.browser)) { throw new Error(` WebDriverIO requires at url and browser to be set. Check your codeceptjs config file to ensure these are set properly { "helpers": { "WebDriverIO": { "url": "YOUR_HOST" "browser": "YOUR_PREFERRED_TESTING_BROWSER" } } } `); } return config; } static _checkRequirements() { try { requireg('webdriverio'); } catch (e) { return ['webdriverio@4']; } } 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() { if (this.options.multiremote) { this.browser = webdriverio.multiremote(this.options.multiremote).init(); } else { this.browser = webdriverio.remote(this.options).init(); } try { await this.browser; } catch (err) { if (err.toString().indexOf('ECONNREFUSED')) { throw new ConnectionRefused(err); } throw err; } this.isRunning = true; if (this.options.timeouts) { await this.defineTimeout(this.options.timeouts); } if (this.options.windowSize === 'maximize') { await this.resizeWindow('maximize'); } else if (this.options.windowSize && this.options.windowSize.indexOf('x') > 0) { const dimensions = this.options.windowSize.split('x'); await this.resizeWindow(dimensions[0], dimensions[1]); } return this.browser; } async _stopBrowser() { if (this.browser && this.isRunning) await this.browser.end(); } 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(); return this.browser; } async _after() { if (!this.isRunning) return; if (this.options.restart) { this.isRunning = false; return this.browser.end(); } if (this.options.keepBrowserState) return; if (!this.options.keepCookies && this.options.desiredCapabilities.browserName) { this.debugSection('Session', 'cleaning cookies and localStorage'); await this.browser.deleteCookie(); } 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.requestHandler.sessionID; 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 = webdriverio.remote(opts).init(); await browser; return browser.requestHandler.sessionID; }, stop: async (sessionId) => { return this.browser.session('DELETE', sessionId); }, loadVars: async (sessionId) => { if (isWithin()) throw new Error('Can\'t start session inside within block'); this.browser.requestHandler.sessionID = sessionId; }, restoreVars: async () => { if (isWithin()) await this._withinEnd(); this.browser.requestHandler.sessionID = defaultSession; }, }; } async _failed(test) { if (isWithin()) await this._withinEnd(); } async _withinBegin(locator) { const frame = isFrameLocator(locator); const client = this.browser; if (frame) { if (Array.isArray(frame)) { withinStore.frame = frame.join('>'); return client .frame(null) .then(() => frame.reduce((p, frameLocator) => p.then(() => this.switchTo(frameLocator)), Promise.resolve())); } withinStore.frame = frame; return this.switchTo(frame); } withinStore.elFn = this.browser.element; withinStore.elsFn = this.browser.elements; this.context = locator; const res = await client.element(withStrictLocator.call(this, locator)); assertElementExists(res, locator); this.browser.element = function (l) { return this.elementIdElement(res.value.ELEMENT, l); }; this.browser.elements = function (l) { return this.elementIdElements(res.value.ELEMENT, l); }; return this.browser; } async _withinEnd() { if (withinStore.frame) { withinStore = {}; return this.switchTo(null); } this.context = this.root; this.browser.element = withinStore.elFn; this.browser.elements = withinStore.elsFn; withinStore = {}; } /** * Get elements by different locator types, including strict locator. * Should be used in custom helpers: * * ```js * this.helpers['WebDriverIO']._locate({name: 'password'}).then //... * ``` * * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator. */ async _locate(locator, smartWait = false) { if (!this.options.smartWait || !smartWait) return this.browser.elements(withStrictLocator.call(this, locator)); this.debugSection(`SmartWait (${this.options.smartWait}ms)`, `Locating ${locator} in ${this.options.smartWait}`); await this.defineTimeout({ implicit: this.options.smartWait }); const els = await this.browser.elements(withStrictLocator.call(this, locator)); await this.defineTimeout({ implicit: 0 }); return els; } /** * Find a checkbox by providing human readable text: * * ```js * this.helpers['WebDriverIO']._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.browser.elements.bind(this)).then(res => res.value); } /** * Find a clickable element by providing human readable text: * * ```js * this.helpers['WebDriverIO']._locateClickable('Next page').then // ... * ``` * * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator. */ async _locateClickable(locator) { return findClickable.call(this, locator, this.browser.elements.bind(this)).then(res => res.value); } /** * Find field elements by providing human readable text: * * ```js * this.helpers['WebDriverIO']._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.value); } /** * Set [WebDriverIO timeouts](http://webdriver.io/guide/testrunner/timeouts.html) in realtime. * Appium: support only web testing. * 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. */ async defineTimeout(timeouts) { try { // try to set W3C compatible timeouts await this.browser.timeouts(timeouts); } catch (error) { if (timeouts.implicit) { await this.browser.timeouts('implicit', timeouts.implicit); } if (timeouts['page load']) { await this.browser.timeouts('page load', timeouts['page load']); } // both pageLoad and page load are accepted // see http://webdriver.io/api/protocol/timeouts.html if (timeouts.pageLoad) { await this.browser.timeouts('page load', timeouts.pageLoad); } if (timeouts.script) { await this.browser.timeouts('script', timeouts.script); } } return this.browser; // return the last response } /** * * 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. * Appium: support only web testing */ 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. * Appium: support */ async click(locator, context = null) { const clickMethod = this.browser.isMobile ? 'touchClick' : 'elementIdClick'; 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).toString()}`); } else { assertElementExists(res, locator, 'Clickable element'); } return this.browser[clickMethod](res.value[0].ELEMENT); } /** * * 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. * Appium: support only web testing */ async doubleClick(locator, context = null) { const clickMethod = this.browser.isMobile ? 'touchClick' : 'elementIdClick'; 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).toString()}`); } else { assertElementExists(res, locator, 'Clickable element'); } const elem = res.value[0]; return this.browser.moveTo(elem.ELEMENT).doDoubleClick(); } /** * * 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. * Appium: support, but in apps works as usual click */ async rightClick(locator) { // just press button if no selector is given if (locator === undefined) { return this.browser.buttonPress('right'); } const res = await this._locate(locator, true); assertElementExists(res, locator, 'Clickable element'); const elem = res.value[0]; if (this.browser.isMobile) return this.browser.touchClick(elem.ELEMENT); return this.browser.moveTo(elem.ELEMENT).buttonPress('right'); } /** * * 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. * Appium: support */ async fillField(field, value) { const res = await findFields.call(this, field); assertElementExists(res, field, 'Field'); const elem = res.value[0]; return this.browser.elementIdClear(elem.ELEMENT).elementIdValue(elem.ELEMENT, 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. * Appium: support, but it's clear a field before insert in apps */ async appendField(field, value) { const res = await findFields.call(this, field); assertElementExists(res, field, 'Field'); const elem = res.value[0]; return this.browser.elementIdValue(elem.ELEMENT, value); } /** * {{> clearField}} * Appium: support */ async clearField(field) { const res = await findFields.call(this, field); assertElementExists(res, field, 'Field'); const elem = res.value[0]; return this.browser.elementIdClear(elem.ELEMENT); } /** * {{> selectOption}} */ async selectOption(select, option) { const res = await findFields.call(this, select); assertElementExists(res, select, 'Selectable field'); const elem = res.value[0]; if (!Array.isArray(option)) { option = [option]; } // select options by visible text let els = await forEachAsync(option, async opt => this.browser.elementIdElements(elem.ELEMENT, Locator.select.byVisibleText(xpathLocator.literal(opt)))); const clickOptionFn = async (el) => { if (el[0]) el = el[0]; if (el && el.ELEMENT) return this.browser.elementIdClick(el.ELEMENT); }; if (Array.isArray(els) && els.length) { return forEachAsync(els, clickOptionFn); } // select options by value els = await forEachAsync(option, async opt => this.browser.elementIdElements(elem.ELEMENT, Locator.select.byValue(xpathLocator.literal(opt)))); if (els.length === 0) { throw new ElementNotFound(select, `Option ${option} in`, 'was found neither by visible text not by 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) { const file = path.join(global.codecept_dir, pathToFile); if (!fileExists(file)) { throw new Error(`File at ${file} can not be found on local system`); } const el = await findFields.call(this, locator); this.debug(`Uploading ${file}`); const res = await this.browser.uploadFile(file); assertElementExists(el, locator, 'File field'); return this.browser.elementIdValue(el.value[0].ELEMENT, res.value); } /** * * 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' : 'elementIdClick'; const locateFn = prepareLocateFn.call(this, context); const res = await findCheckable.call(this, field, locateFn); assertElementExists(res, field, 'Checkable'); const elem = res.value[0]; const isSelected = await this.browser.elementIdSelected(elem.ELEMENT); if (isSelected.value) return Promise.resolve(true); return this.browser[clickMethod](elem.ELEMENT); } /** * * 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' : 'elementIdClick'; const locateFn = prepareLocateFn.call(this, context); const res = await findCheckable.call(this, field, locateFn); assertElementExists(res, field, 'Checkable'); const elem = res.value[0]; const isSelected = await this.browser.elementIdSelected(elem.ELEMENT); if (!isSelected.value) return Promise.resolve(true); return this.browser[clickMethod](elem.ELEMENT); } /** * * 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 * Appium: support */ async grabTextFrom(locator) { const res = await this._locate(locator, true); assertElementExists(res, locator); const val = await forEachAsync(res.value, async el => this.browser.elementIdText(el.ELEMENT)); 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 * Appium: support only web testing */ async grabHTMLFrom(locator) { const html = await this.browser.getHTML(withStrictLocator.call(this, locator)); this.debugSection('Grab', html); return html; } /** * * 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 * Appium: support only web testing */ async grabValueFrom(locator) { const res = await this._locate(locator, true); assertElementExists(res, locator); return forEachAsync(res.value, async el => this.browser.elementIdAttribute(el.ELEMENT, 'value')); } /** * * 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.value, async el => this.browser.elementIdCssProperty(el.ELEMENT, 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.value, async el => this.browser.elementIdAttribute(el.ELEMENT, attr)); } /** * * Checks that title contains text. ```js I.seeInTitle('Home Page'); ``` @param {string} text text value to check. * Appium: support only web testing */ 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. * Appium: support only web testing */ 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 * Appium: support only web testing */ 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. * Appium: support with context in apps */ 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. * Appium: support with context in apps */ 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. * Appium: support only web testing */ 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. * Appium: support only web testing */ 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. * Appium: support */ async seeElement(locator) { const res = await this._locate(locator, true); if (!res.value || res.value.length === 0) { return truth(`elements of ${locator}`, 'to be seen').assert(false); } const selected = await forEachAsync(res.value, async el => this.browser.elementIdDisplayed(el.ELEMENT)); return truth(`elements of ${locator}`, 'to be seen').assert(selected); } /** * {{> dontSeeElement}} * Appium: support */ async dontSeeElement(locator) { const res = await this._locate(locator, false); if (!res.value || res.value.length === 0) { return truth(`elements of ${locator}`, 'to be seen').negate(false); } const selected = await forEachAsync(res.value, async el => this.browser.elementIdDisplayed(el.ELEMENT)); 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. * Appium: support */ async seeElementInDOM(locator) { const res = await this.browser.elements(withStrictLocator.call(this, locator)); return empty('elements').negate(res.value); } /** * * 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. * Appium: support */ async dontSeeElementInDOM(locator) { const res = await this.browser.elements(withStrictLocator.call(this, locator)); return empty('elements').assert(res.value); } /** * * 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. * Appium: support */ async seeInSource(text) { const source = await this.browser.getSource(); 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 * Appium: support */ async grabSource() { return this.browser.getSource(); } /** * Get JS log from browser. Log buffer is reset after each request. * * ```js * let logs = await I.grabBrowserLogs(); * console.log(JSON.stringify(logs)) * ``` */ async grabBrowserLogs() { return this.browser.log('browser').then(res => res.value); } /** * * 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.url(); return res.value; } async grabBrowserUrl() { console.log('grabBrowserUrl deprecated. Use grabCurrentUrl instead'); const res = await this.browser.url(); return res.value; } /** * * 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. * Appium: support */ async dontSeeInSource(text) { const source = await this.browser.getSource(); 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. * Appium: support * * ```js * I.seeNumberOfElements('#submitBtn', 1); * ``` * * @param {CodeceptJS.LocatorOrString} locator element located by CSS|XPath|strict locator. * @param {number} [num] number of elements. */ async seeNumberOfElements(locator, num) { const res = await this._locate(withStrictLocator.call(this, locator)); return assert.equal(res.value.length, num, `expected number of elements (${locator}) is ${num}, but found ${res.value.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. */ 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.value.length; let props = await forEachAsync(res.value, async (el) => { return forEachAsync(Object.keys(cssProperties), async (prop) => { const propValue = await this.browser.elementIdCssProperty(el.ELEMENT, 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.value.length; let attrs = await forEachAsync(res.value, async (el) => { return forEachAsync(Object.keys(attributes), async attr => this.browser.elementIdAttribute(el.ELEMENT, 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 elements by locator. ```js let numOfElements = await I.grabNumberOfVisibleElements('p'); ``` @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator. @returns {Promise<number>} number of visible elements */ async grabNumberOfVisibleElements(locator) { const res = await this._locate(locator); let selected = await forEachAsync(res.value, async el => this.browser.elementIdDisplayed(el.ELEMENT)); if (!Array.isArray(selected)) selected = [selected]; selected = selected.filter(val => val === true); return selected.length; } /** * * Checks that current url contains a provided fragment. ```js I.seeInCurrentUrl('/register'); // we are on registration page ``` @param {string} url a fragment to check * Appium: support only web testing */ async seeInCurrentUrl(url) { const res = await this.browser.url(); return stringIncludes('url').assert(url, decodeUrl(res.value)); } /** * * Checks that current url does not contain a provided fragment. @param {string} url value to check. * Appium: support only web testing */ async dontSeeInCurrentUrl(url) { const res = await this.browser.url(); return stringIncludes('url').negate(url, decodeUrl(res.value)); } /** * * Checks that current url is equal to provided one. If a relative url provided, a configured url will be prepended to it. So both examples will work: ```js I.seeCurrentUrlEquals('/register'); I.seeCurrentUrlEquals('http://my.site.com/register'); ``` @param {string} url value to check. * Appium: support only web testing */ async seeCurrentUrlEquals(url) { const res = await this.browser.url(); return urlEquals(this.options.url).assert(url, decodeUrl(res.value)); } /** * * Checks that current url is not equal to provided one. If a relative url provided, a configured url will be prepended to it. ```js I.dontSeeCurrentUrlEquals('/login'); // relative url are ok I.dontSeeCurrentUrlEquals('http://mysite.com/login'); // absolute urls are also ok ``` @param {string} url value to check. * Appium: support only web testing */ async dontSeeCurrentUrlEquals(url) { const res = await this.browser.url(); return urlEquals(this.options.url).negate(url, decodeUrl(res.value)); } /** * * Executes sync script on a page. Pass arguments to function as additional parameters. Will return execution result to a test. In this case you should use async function and await to receive results. Example with jQuery DatePicker: ```js // change date of jQuery DatePicker I.executeScript(function() { // now we are inside browser context $('date').datetimepicker('setDate', new Date()); }); ``` Can return values. Don't forget to use `await` to get them. ```js let date = await I.executeScript(function(el) { // only basic types can be returned return $(el).datetimepicker('getDate').toString(); }, '#date'); // passing jquery selector ``` @param {string|function} fn function to be executed in browser context. @param {...any} args to be passed to function. @return {Promise<any>} * Appium: support only web testing * * Wraps [execute](http://webdriver.io/api/protocol/execute.html) command. */ executeScript(fn) { return this.browser.execute.apply(this.browser, arguments).then(res => res.value); } /** * * Executes async script on page. Provided function should execute a passed callback (as first argument) to signal it is finished. Example: In Vue.js to make components completely rendered we are waiting for [nextTick](https://vuejs.org/v2/api/#Vue-nextTick). ```js I.executeAsyncScript(function(done) { Vue.nextTick(done); // waiting for next tick }); ``` By passing value to `done()` function you can return values. Additional arguments can be passed as well, while `done` function is always last parameter in arguments list. ```js let val = await I.executeAsyncScript(function(url, done) { // in browser context $.ajax(url, { success: (data) => done(data); } }, 'http://ajax.callback.url/'); ``` @param {string|function} fn function to be executed in browser context. @param {...any} args to be passed to function. @return {Promise<any>} * Appium: support only web testing */ executeAsyncScript(fn) { return this.browser.executeAsync.apply(this.browser, arguments).then(res => res.value); } /** * Scrolls to element matched by locator. * Extra shift can be set with offsetX and offsetY options. * * ```js * I.scrollTo('footer'); * I.scrollTo('#submit', 5, 5); * ``` * * @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator. * @param {number} [offsetX=0] (optional) X-axis offset. * @param {number} [offsetY=0] (optional) Y-axis offset. */ /** * * Scrolls to element matched by locator. Extra shift can be set with offsetX and offsetY options. ```js I.scrollTo('footer'); I.scrollTo('#submit', 5, 5); ``` @param {CodeceptJS.LocatorOrString} locator located by CSS|XPath|strict locator. @param {number} [offsetX=0] (optional, `0` by default) X-axis offset. @param {number} [offsetY=0] (optional, `0` by default) Y-axis offset. * Appium: support only web testing */ async scrollTo(locator, offsetX = 0, offsetY = 0) { if (typeof locator === 'number' && typeof offsetX === 'number') { offsetY = offsetX; offsetX = locator; locator = null; } if (locator) { const res = await this._locate(withStrictLocator.call(this, locator), true); if (!res.value || res.value.length === 0) { return truth(`elements of ${locat