Best JavaScript code snippet using chromy
Selector.js
Source:Selector.js
1var helper = require("./helper.js");2var enums = require('./Enums.js');3var botError = require('./BotError.js');4class Selector{5 constructor(name, selectorDict){6 this._action = (selectorDict.type)? getType(selectorDict.type): null;7 this._parent = selectorDict.parent;8 this._name = name;9 this._linked = (selectorDict.linked)? selectorDict.linked : null;10 this._event = (selectorDict.event)? selectorDict.event : null;11 this._isOptional = selectorDict.isOptional;12 this._ignoreAttribute = (selectorDict.ignoreAttribute) ? selectorDict.ignoreAttribute : null;13 this._ignoreValue = (selectorDict.ignoreValue)? selectorDict.ignoreValue : null;14 this._cheapestIndicatorAttribute = (selectorDict.cheapestIndicatorAttribute) ? selectorDict.cheapestIndicatorAttribute : null;15 this._cheapestIndicator = (selectorDict.cheapestIndicator)? selectorDict.cheapestIndicator : null;16 this._objectName = (selectorDict.value)? selectorDict.value : null;17 this._expression = (selectorDict.expression)? selectorDict.expression : null;18 this._raise = (selectorDict.raise)? selectorDict.raise : null;19 this._isRoot = (selectorDict.isRoot)? (selectorDict.isRoot): false;20 this._waitSelector = (selectorDict.waitSelector)? (selectorDict.waitSelector): null;21 this._applyBusinessRules = (selectorDict.applyBusinessRules)? (selectorDict.applyBusinessRules): false;22 this._flightType = (selectorDict.flightType)? (selectorDict.flightType): null;23 this._attributes = {24 "ByXpath": selectorDict.ByXpath || null,25 "ById": selectorDict.ById,26 "ByClass": (selectorDict.ByClass)? selectorDict.ByClass.match(/[^ ,]+/g).join('.') : null,27 "ByCssXpath": selectorDict.ByCssXpath || null28 };29 }30 /**31 * @return {integer}32 */33 action() {34 return this._action;35 }36 /**37 * @return {dictionary}38 */39 expression() {40 return this._expression;41 }42 /**43 * @return {string}44 */45 parent() {46 return this._parent;47 }48 /**49 * @return {string}50 */51 name() {52 return this._name;53 }54 /**55 * @return {string}56 */57 linked() {58 return this._linked;59 }60 /**61 */62 set setLinked(value) {63 this._linked = value;64 }65 /**66 * @return {string}67 */68 event() {69 return this._event;70 }71 /**72 */73 set setEvent(value) {74 this._event = value;75 }76 /**77 * @return {boolean}78 */79 isOptional(){80 return this._isOptional;81 }82 /**83 * @return {string}84 */85 ignoreAttribute() {86 return this._ignoreAttribute;87 }88 /**89 * @return {string}90 */91 ignoreValue() {92 return this._ignoreValue;93 }94 /**95 * @return {string}96 */97 objectName() {98 return this._objectName;99 }100 /**101 * @return {string}102 */103 raise() {104 return this._raise;105 }106 /**107 * @return {boolean}108 */109 isRoot(){110 return this._isRoot;111 }112 /**113 * @return {string}114 */115 cheapestIndicatorAttribute() {116 return this._cheapestIndicatorAttribute;117 }118 /**119 * @return {string}120 */121 cheapestIndicator() {122 return this._cheapestIndicator;123 }124 /**125 * @return {string}126 */127 waitSelector() {128 return this._waitSelector;129 }130 /**131 * @return {boolean}132 */133 applyBusinessRules(){134 return this._applyBusinessRules;135 }136 /**137 * @return {string}138 */139 flightType() {140 return this._flightType;141 }142 static create(name, selectorDict){143 return new Selector(name, selectorDict);144 }145}146Selector.prototype.value = async function(page, monitoring, element=null) {147 if (!element) element=page;148 try{149 return await helper.getSelectorValue(page, element, this._attributes);150 }catch (e){151 if (this._isOptional){152 if (!('not_scraped_items_optional' in monitoring.getFailedElements())){153 monitoring.getFailedElements()['not_scraped_items_optional'] = [];154 }155 if (!monitoring.getFailedElements()['not_scraped_items_optional'].includes(this._name)){156 monitoring.getFailedElements()['not_scraped_items_optional'].push(this._name);157 }158 return null;159 }else {160 if (!('not_scraped_items' in monitoring.getFailedElements())){161 monitoring.getFailedElements()['not_scraped_items'] = [];162 }163 if (!monitoring.getFailedElements()['not_scraped_items'].includes(this._name)){164 monitoring.getFailedElements()['not_scraped_items'].push(this._name);165 }166 throw new botError.HTMLTagsError(this._name + " selector could not be found.");167 }168 }169 return helper.getSelectorValue(page, element, this._attributes);170}171Selector.prototype.element = async function(page, monitoring, element=null) {172 if (!element) element=page;173 try{174 return await helper.getSelector(page, element, this._attributes);175 }catch (e){176 if (this._isOptional){177 if (!('not_scraped_items_optional' in monitoring.getFailedElements())){178 monitoring.getFailedElements()['not_scraped_items_optional'] = [];179 }180 if (!monitoring.getFailedElements()['not_scraped_items_optional'].includes(this._name)){181 monitoring.getFailedElements()['not_scraped_items_optional'].push(this._name);182 }183 return null;184 }else {185 if (!('not_scraped_items' in monitoring.getFailedElements())){186 monitoring.getFailedElements()['not_scraped_items'] = [];187 }188 if (!monitoring.getFailedElements()['not_scraped_items'].includes(this._name)){189 monitoring.getFailedElements()['not_scraped_items'].push(this._name);190 }191 throw new botError.HTMLTagsError(this._name + " selector could not be found.");192 }193 }194}195Selector.prototype.elements = async function(page, monitoring, element=null) {196 if (!element) element=page;197 try{198 return await helper.getSelectors(page, element, this._attributes);199 }catch (e){200 if (this._isOptional){201 if (!('not_scraped_items_optional' in monitoring.getFailedElements())){202 monitoring.getFailedElements()['not_scraped_items_optional'] = [];203 }204 if (!monitoring.getFailedElements()['not_scraped_items_optional'].includes(this._name)){205 monitoring.getFailedElements()['not_scraped_items_optional'].push(this._name);206 }207 return null;208 }else {209 if (!('not_scraped_items' in monitoring.getFailedElements())){210 monitoring.getFailedElements()['not_scraped_items'] = [];211 }212 if (!monitoring.getFailedElements()['not_scraped_items'].includes(this._name)){213 monitoring.getFailedElements()['not_scraped_items'].push(this._name);214 }215 throw new botError.HTMLTagsError(this._name + " selector could not be found.");216 }217 }218}219Selector.prototype.setElementValue = function(page, value) {220 return helper.setElementValue(page, this._attributes, value);221}222class Selectors{223 static create(selectors, configuration){224 let selectorList = [];225 let removedLinkedItems = [];226 for (let i=0; i < Object.keys(selectors).length; i++){227 if (!(isDependencySatisfied(selectors[Object.keys(selectors)[i]], configuration))){228 if (selectors[Object.keys(selectors)[i]]['linked']) removedLinkedItems.push([Object.keys(selectors)[i],229 selectors[Object.keys(selectors)[i]]['linked'],230 selectors[Object.keys(selectors)[i]]['event']231 ])232 continue;233 }234 selectorList.push(Selector.create(Object.keys(selectors)[i], selectors[Object.keys(selectors)[i]]));235 }236 for (let _removedLinkItem of removedLinkedItems){237 let rootParentTag = getRootParent(_removedLinkItem[0]);238 function getRootParent(selectorName){239 let parentTag = Object.entries(selectors).filter(([k,v]) => k == selectorName).map(([k,v]) => (v['parent']))[0];240 if (!parentTag) return selectorName;241 return getRootParent(parentTag);242 }243 selectorList.map(el => {244 if(el._linked == rootParentTag)245 el.setLinked = _removedLinkItem[1];246 //el.setEvent = _removedLinkItem[2];247 return el248 });249 }250 return selectorList;251 }252}253function getType(_type){254 switch(_type){255 case enums.tagTypeEnums.get("click").key:256 return enums.tagTypeEnums.get("click").value;257 case enums.tagTypeEnums.get("input").key:258 return enums.tagTypeEnums.get("input").value;259 case enums.tagTypeEnums.get("select").key:260 return enums.tagTypeEnums.get("select").value;261 case enums.tagTypeEnums.get("extractor").key:262 return enums.tagTypeEnums.get("extractor").value;263 case enums.tagTypeEnums.get("calendar").key:264 return enums.tagTypeEnums.get("calendar").value;265 case enums.tagTypeEnums.get("linked").key:266 return enums.tagTypeEnums.get("linked").value;267 case enums.tagTypeEnums.get("closed").key:268 return enums.tagTypeEnums.get("closed").value;269 case enums.tagTypeEnums.get("dropdown").key:270 return enums.tagTypeEnums.get("dropdown").value;271 }272}273function isDependencySatisfied(_selector, _configuration){274 if (!('dependency' in _selector) || (!_selector['dependency'])) return true;275 if (('dependency' in _selector) || (_selector['dependency'])){276 let conditions = _selector['dependency'].split(',');277 for (let _condition of conditions){278 let conditionTextArray = _condition.split(' ');279 let _flagObject = flagToObject(conditionTextArray[0], _configuration);280 let _flagObjectValue = flagToObject(conditionTextArray[2], _configuration);281 if (conditionTextArray[1] == "is"){282 return (_flagObject == _flagObjectValue);283 }284 if (conditionTextArray[1] == "greater than"){285 return (_flagObject > _flagObjectValue);286 }287 if (conditionTextArray[1] == "less than"){288 return (_flagObject < _flagObjectValue);289 }290 }291 }292 return true;293}294function flagToObject(string, configuration){295 if (/^\d+$/.test(string)) return parseInt(string);296 switch (string.toLowerCase()) {297 case "roundtrip":298 return configuration.parameters().isRoundtrip();299 case "depth":300 return configuration.parameters().depth();301 case "true":302 return true;303 case "false":304 return false;305 break;306 default:307 }308}...
app.js
Source:app.js
...10 };11 const _createPage = async browser => await browser.newPage();12 const _openPage = async page => {13 await page.goto(_hashtagUrl, { waitUntil: 'networkidle2' });14 await _waitSelector(page, '.yQ0j1');15 };16 const _waitSelector = async (page, selector) => {17 await page.waitForSelector(selector);18 };19 const _wait = async (page, time) => {20 await page.waitFor(time);21 };22 const _getPosts = async page => {23 const posts = await page.$$('.FFVAD[src]');24 posts.splice(0, 9);25 return posts;26 };27 const _openModal = async (page, post) => {28 post.click();29 await _waitSelector(page, '.M9sTE ._97aPb');30 await _wait(page, 1000);31 };32 const _getItemUrl = async page => {33 let item = await page.$('._97aPb .tWeCl[src]');34 if (item == null) {35 item = await page.$('._97aPb .FFVAD[src]');36 }37 return page.evaluate(link => link.getAttribute('src'), item);38 };39 const _closeModal = async page => {40 await page.$eval('.TxciK .wpO6b', element => {41 element.click();42 });43 await page.waitFor(500);...
PopupWithForm.js
Source:PopupWithForm.js
1import Popup from './Popup.js';2export default class PopupWithForm extends Popup {3 constructor(popupSelector, submitForm) {4 super(popupSelector);5 this._submitForm = submitForm;6 this._formElement = this._modalWindow.querySelector('.popup__form');7 this._submitButton = this._modalWindow.querySelector('.popup__submit');8 this._waitSelector = 'popup__submit_wait';9 }10 _getInputValues() {11 this._inputList = this._modalWindow.querySelectorAll('.popup__input');12 this._formValues = {};13 this._inputList.forEach(input => this._formValues[input.name] = input.value);14 return this._formValues;15 }16 setEventListeners() {17 super.setEventListeners();18 this._formElement.addEventListener('submit', (evt) => {19 evt.preventDefault();20 21 this._submitButton.classList.add(this._waitSelector);22 this._handleFormSubmit();23 } )24 }25 26 fillInputs(data){27 28 this._inputList = this._modalWindow.querySelectorAll('.popup__input');29 this._inputList.forEach(input =>input.value=data[input.name] );30 }31 _clearInputs(){32 this._formElement.reset();33 }34 _handleFormSubmit() {35 this._submitForm(event ,this._getInputValues());36 37 }38 closePopup() {39 super.closePopup();40 41 this._formElement.removeEventListener('submit', (evt) => {42 evt.preventDefault();43 this._handleFormSubmit()44 });45 this._clearInputs();46 this._submitButton.classList.remove(this._waitSelector);47 48 }49 openPopup() {50 super.openPopup();51 }...
Using AI Code Generation
1module.exports = function (chromy, scenario, vp) {2 console.log('SCENARIO > ' + scenario.label);3 require('./clickAndHoverHelper')(chromy, scenario);4 chromy.waitSelector('div#myDiv');5};6module.exports = function (chromy, scenario) {7 require('./clickAndHoverHelper')(chromy, scenario);8 chromy.click('a#myLink');9 chromy.hover('button#myButton');10};11module.exports = function (chromy, scenario) {12 require('./clickAndHoverHelper')(chromy, scenario);13 chromy.click('a#myLink');14 chromy.hover('button#myButton');15};16module.exports = function (chromy, scenario) {17 require('./clickAndHoverHelper')(chromy, scenario);18 chromy.click('a#myLink');19 chromy.hover('button#myButton');20};21module.exports = function (chromy, scenario) {22 require('./clickAndHoverHelper')(chromy, scenario);23 chromy.click('a#myLink');24 chromy.hover('button#myButton');25};26module.exports = function (chromy, scenario) {27 require('./clickAndHoverHelper')(chromy, scenario);28 chromy.click('a#myLink');29 chromy.hover('button#myButton');30};31module.exports = function (chromy, scenario) {32 require('./clickAndHoverHelper')(chromy, scenario);
Using AI Code Generation
1const chromy = require('chromy');2chromy.chain()3 .wait(1000)4 .type('input[name="q"]', 'Hello World')5 .wait(1000)6 .type('input[name="q"]', chromy.keys.ENTER)7 .wait(1000)8 .screenshot()9 .end()10 .then(function(result) {11 console.log(result);12 })13 .catch(function(err) {14 console.log(err);15 });16chromy.close();
Using AI Code Generation
1chromy = new Chromy({visible: true});2chromy.chain()3 .waitSelector('input[name="q"]')4 .type('input[name="q"]', 'Hello world')5 .click('input[name="btnK"]')6 .wait(5000)7 .end()8 .then(function() {9 console.log('Done');10 })11 .catch(function(err) {12 console.error(err);13 });14chromy.close();15chromy.waitSelector('input[name="q"]', 5000);
Using AI Code Generation
1const chromy = require('chromy');2chromy.chain()3 .waitSelector('a')4 .end()5 .then(_ => chromy.close())6 .catch(_ => chromy.close());7const chromy = require('chromy');8chromy.chain()9 .waitSelector('a')10 .evaluate(_ => {11 return document.querySelector('a').href;12 })13 .end()14 .then(result => {15 console.log(result);16 chromy.close();17 })18 .catch(_ => chromy.close());
Using AI Code Generation
1var chromy = require('chromy');2chromy.chain()3 .waitSelector('input[name="q"]')4 .screenshot('google.png')5 .end()6 .then(function() {7 console.log('done');8 })9 .catch(function(e) {10 console.log('error');11 console.log(e);12 });13var puppeteer = require('puppeteer');14(async () => {15 const browser = await puppeteer.launch();16 const page = await browser.newPage();17 await page.waitForSelector('input[name="q"]');18 await page.screenshot({path: 'google.png'});19 await browser.close();20})();21var Nightmare = require('nightmare');22var nightmare = Nightmare({ show: true });23 .wait('input[name="q"]')24 .screenshot('google.png')25 .end()26 .then(function() {27 console.log('done');28 })29 .catch(function(e) {30 console.log('error');31 console.log(e);32 });33var casper = require('casper').create();34 this.waitForSelector('input[name="q"]');35 this.capture('google.png');36});37casper.run(function() {38 this.echo('done').exit();39});40var page = require('webpage').create();41 page.evaluate(function() {42 $(function() {43 $('input[name="q"]').on('change', function() {44 phantom.exit();45 });46 });47 });48 });49});50var webdriver = require('selenium-webdriver');51var By = webdriver.By;52var until = webdriver.until;53var driver = new webdriver.Builder()54 .forBrowser('chrome')55 .build();56driver.wait(until.elementLocated(By.css('input[name="q"]')), 10000);57driver.takeScreenshot().then(function(data
Using AI Code Generation
1var chromy = new Chromy({ port: 9222 });2chromy.chain()3 .wait(1000)4 .screenshot()5 .end(function(err, data) {6 });7var chromy = new Chromy({ port: 9222 });8chromy.chain()9 .wait(function() {10 return document.querySelector('h1').innerText === 'Example Domain';11 })12 .screenshot()13 .end(function(err, data) {14 });15var chromy = new Chromy({ port: 9222 });16chromy.chain()17 .waitUntil(function() {18 return document.querySelector('h1').innerText === 'Example Domain';19 })20 .screenshot()21 .end(function(err, data) {22 });23var chromy = new Chromy({ port: 9222 });24chromy.chain()25 .waitUntil(function() {26 return document.querySelector('h1').innerText === 'Example Domain';27 })28 .screenshot()29 .end(function(err, data) {30 });31var chromy = new Chromy({ port: 9222 });32chromy.chain()33 .waitUntil(function() {34 return document.querySelector('h1').innerText === 'Example Domain';35 })36 .screenshot()37 .end(function(err, data) {38 });39var chromy = new Chromy({ port: 9222 });40chromy.chain()41 .waitUntil(function() {42 return document.querySelector('h1').innerText === 'Example Domain';43 })
Using AI Code Generation
1const Chromy = require('chromy')2const chromy = new Chromy({visible: true})3chromy.chain()4 .type('input[name="q"]', 'hello world')5 .click('input[name="btnK"]')6 .wait(1000)7 .evaluate(() => {8 })9 .result((title) => {10 console.log(title)11 })12 .end()13 .then(() => {14 console.log('done')15 })16 .catch((err) => {17 console.error(err)18 })19const Chromy = require('chromy')20const chromy = new Chromy({visible: true})21chromy.chain()22 .type('input[name="q"]', 'hello world')23 .waitSelector('input[name="btnK"]')24 .click('input[name="btnK"]')25 .wait(1000)26 .evaluate(() => {27 })28 .result((title) => {29 console.log(title)30 })31 .end()32 .then(() => {33 console.log('done')34 })35 .catch((err) => {36 console.error(err)37 })38const Chromy = require('chromy')39const chromy = new Chromy({visible: true})40chromy.chain()41 .type('input[name="q"]', 'hello world')42 .click('input[name="btnK"]')43 .wait(1000)44 .evaluate(() => {45 })46 .result((title) => {47 console.log(title)48 })49 .end()50 .then(() => {51 console.log('done')52 })53 .catch((err) => {
Using AI Code Generation
1chromy.waitSelector('div#main').then(function(){2 console.log('selector found');3 chromy.wait(1000).then(function(){4 chromy.screenshot({path: 'screenshot.png'}).then(function(){5 chromy.close();6 });7 });8});9chromy.wait(5000).then(function(){10 chromy.screenshot({path: 'screenshot.png'}).then(function(){11 chromy.close();12 });13});14chromy.waitFor(function(){15 return document.querySelector('div#main') !== null;16}).then(function(){17 console.log('selector found');18 chromy.wait(1000).then(function(){19 chromy.screenshot({path: 'screenshot.png'}).then(function(){20 chromy.close();21 });22 });23});24chromy.waitFor(function(){25 return document.querySelector('div#main') !== null;26}, 5000).then(function(){27 console.log('selector found');28 chromy.wait(1000).then(function(){29 chromy.screenshot({path: 'screenshot.png'}).then(function(){30 chromy.close();31 });32 });33});34chromy.waitFor(function(){35 return document.querySelector('div#main') !== null;36}, 5000, 100).then(function(){37 console.log('selector found');38 chromy.wait(1000).then(function(){39 chromy.screenshot({path: 'screenshot.png'}).then(function(){40 chromy.close();41 });42 });43});44chromy.waitFor(function(){45 return document.querySelector('div#main') !== null;46}, 5000, 100, 'selector found').then(function(){47 console.log('selector found');48 chromy.wait(1000).then(function(){49 chromy.screenshot({path: 'screenshot.png'}).then(function(){50 chromy.close();51 });52 });53});54chromy.waitFor(function(){55 return document.querySelector('div#main') !== null;56}, 5000, 100, 'selector found').then(function(){57 console.log('selector found');
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!