Find all clickable elements using webdriverio - webdriver-io

I am new to webdriver io and I want to get all clickable elements using webdriver io and iterate through them. I came across 'browser.findElements' API, but could not get it to work. Can anyone provide me a sample code ?
var assert = require('assert');
var homePage = require("../../pages/home_page");
describe('Keyboard friendly home page', () => {
it('User should be able to navigate using tab',() => {
browser.url(homePage.url);
elements = browser.findElements("div");
clickableElements = [];
elements.forEach(element => {
if (element.isDiplayed() && element.isClickable()) {
clickableElements.push(element);
}
});
clickableElements.array.forEach(element => {
console.log(elemtent.getText() + "is clickable");
});
});
});

There might be two problems with your example:
incorrect use of findElements, see documentation; you can use $$ command where you pass only a selector, no need to pass a location strategy as well
the last forEach loop should look like this:
clickableElements.forEach(element => {
console.log(elemtent.getText() + "is clickable");
});

Related

Vue Reading in parallel in a loop

I have an Set array which contains multiple Ids.I would like to loop through the Set and make the api calls in parallel for each id and get back the user object, add it to a map.How can i achieve it.
The value is Set
userIds :Set[2]
0:"1"
1:"2"
data() {
return {
userIds: new Set(),
};
},
const res = getUsers(userId)
hope it will resolve your issues. i did not test, just writing code here directly.
// set requests
let allRequests = []
//you can use other loop based on your decession
this.userIds.forEach(id => { allRequests.push(axios.get(`your_url\${id}`)) })
// you can use await it is based on you requirement
axios.all(allRequests).then(axios.spread((...responses) => {
//make your map here using responses
})).catch(errors => {
// react on errors.
})
you can check this reference

How can i create multiple editors whit class name

I try to create multiple ckeditors classic.
The problem is that i dont know how many i will have. So i init them by className.
This init the editors and work, but dont send anything trough ajax. So when i try to update the textarea only i can send the last editor because window.editor is overwrite.
I try then to store in an array but i cant pass th for neditor value because its a then so it executes when the for loop is done, so neditor is always 2.
How can i made it work? Idont understand very well promises
Thanks!
import ClassicEditor from './ckeditor5-build-classic';
var allEditors = document.querySelectorAll('.usarCkeditor');//i have 2 editors in that case
for (var neditores = 0; neditores < allEditors.length; neditores++) {
ClassicEditor.create(allEditors[neditores])
.then(editor => {
window.editor = editor;//window.editor is alway the last editor
})
.catch(err => {
console.error(err.stack);
});
}
This is other version :
for (var neditores = 0; neditores < allEditors.length; neditores++) {
window["editor" + neditores] = 'paco';
ClassicEditor.create(document.querySelector('#' + allEditors[neditores].attributes.id.value))
.then(editor => {
console.log(editor);
window["editor" + neditores] = editor;
console.log(neditores);//always 2 so it overwrites the array
})
.catch(err => {
console.error(err.stack);
});
}
//window.editor -> [0] = 'paco';[1] = 'paco';[2]= ckeditor
Please notice that querySelectorAll returns an HTMLNodeList not an Array.
If you want to initialize editor over multiple elements with classes you can do it for example in this way. All references to editors instances will be stored in window.editors object.
window.editors = {};
document.querySelectorAll( '.editor' ).forEach( ( node, index ) => {
ClassicEditor
.create( node, {} )
.then( newEditor => {
window.editors[ index ] = newEditor
} );
} );
This is a working sample: https://codepen.io/msamsel/pen/pXONjB?editors=1010

CucumberJS tests passing even though it's not possible

I'm trying to convert some old ruby tests (which used cucumber, phantomjs and capybara) into JavaScript (using cucumber, phantomjs and selenium) as my project is 100% node based and I want to remove the Ruby dependency.
When I run the tests, they all pass. The problem is, I've not created the conditions for the test to pass yet so a pass is impossible. I'm not sure where I'm going wrong.
Here is my world.js file:
var {defineSupportCode} = require('cucumber');
var seleniumWebdriver = require('selenium-webdriver'),
By = seleniumWebdriver.By,
until = seleniumWebdriver.until;
function CustomWorld() {
this.driver = new seleniumWebdriver.Builder()
.withCapabilities(seleniumWebdriver.Capabilities.phantomjs())
.build()
// Returns a promise that resolves to the element
this.waitForElement = function(locator) {
var condition = seleniumWebdriver.until.elementLocated(locator);
return this.driver.wait(condition)
}
}
defineSupportCode(function({setWorldConstructor}) {
setWorldConstructor(CustomWorld)
});
And here is my step definitions file:
require('dotenv').config();
var chalk = require('chalk');
var {defineSupportCode} = require('cucumber');
var seleniumWebdriver = require('selenium-webdriver'),
By = seleniumWebdriver.By,
until = seleniumWebdriver.until;
defineSupportCode(function({ Given, When, Then }) {
Given(/^I show my environment$/, function (next) {
console.log(chalk.green("Running against:" + process.env.TARGET_URI))
next()
})
When(/^I visit "(.*?)"$/, function (url) {
return this.driver.get(url);
})
Then(/^I should be on "([^"]*)"$/, function(page_name) {
this.driver.get(process.env.TARGET_URI+'/'+page_name)
.then(function() {
return this.driver.getCurrentUrl();
})
})
Then(/^I should see "([^"]*)"$/, function (text) {
var xpath = "//*[contains(text(),'" + text + "')]";
var condition = seleniumWebdriver.until.elementLocated({xpath: xpath});
return this.driver.wait(condition, 5000);
});
})
The only possible tests that could be passing there are: When(/^I visit "(.*?)"$/... and Given(/^I show my environment$/...
For reference, here is my .feature file too:
Feature: Test the global header works as expected
Scenario: Header components should exist
Given I visit "/hello"
Then I expect to see a ".c-logo-bar" element
And I expect to see a ".c-search-bar" element
And I expect to see a ".c-main-nav-bar" element
Any ideas where I'm going wrong?

Accessing elements using $$ or elements in webdriverio

I want to access web elements using the $$ or elements command using webdriverio. I know they return array of web elements but I am facing tough time accessing them, probably because I am new to webdriverio.
I tried the below code:
var webdriverio = require('webdriverio');
var options = {
desiredCapabilities: {
browserName: 'firefox',
},
};
var client = webdriverio.remote(options);
client
.init()
.url(some url)
.isExisting(selector).then(function(isExisting)) {
if(isExisting) {
var bText = this.$$('textarea[name="message_text]') // this code onwards it is not working
bText.then(function (res) {
console.log(res.length);
console.log(res);
res.value.forEach(function (elem) {
return this.click(elem.ELEMENT)
.setValue(elem.ELEMENT,'some text')
.keys('Enter')
})
})
In the above code, I can see the array res in console but the forEach loop doesn't seem to work. I want to perform click, setValue and keys('Enter') for each of the element present in this.$$('textarea[name="message_text"]') also not able to understand why the returned elements are in a form of JSON objects?
If anyone could guide me in right direction that would help!
Use 'client' instead of 'this' to select the elements.
var bText = client.$$('textarea[name="message_text]') // this code onwards it is not working
bText.then(function (res) {
console.log(res.length);
console.log(res);
See use of runner here -
https://github.com/webdriverio/webdriverio/issues/1043
#ChristianB's suggestion worked actually,since webdriverio's standalone app is built on top of webdriverjs whose methods return promises we need to resolve them properly.I was able to do this using map & Promise.all :
var bText = this.$$('textarea[name="message_text]')
bText.then(function (res) {
console.log(res.length);
console.log(res);
var promises = res.map(function (elem) {
return client
.elementIdClick(elem.ELEMENT)
.setValue(elem.selector,'some text')
.keys('Enter')
})
return Promise.all(promises)
})

Check if image is valid and loaded with Protractor

I am writing tests using Protractor (with Cucumber.js, Chai and Chai As Promised, though I think these details don't matter). I would like to write a test that checks whether an image element is valid and loaded - i.e. that it has a src attribute and has not errored out while loading.
There are some nice-looking answers elsewhere to the question of how to check if an image is loaded from within a browser, via the DOM API. But how can I cleanly perform this check using Protractor's API?
I expect my test will look something like:
this.Then(/^I should see the "([^"]*)" image$/, function (imageId, callback) {
expect(
element(by.id(imageId))
).to.eventually.satisfy(isImageOk).notify(callback);
});
but I don't know how to implement the isImageOk function via the Protractor API.
You need to evaluate a JavaScript expression in the context of the browser, using Protractor's executeAsyncScript function.
Here is the code from my answer to a similar question:
it('should find all images', function () {
browser.executeAsyncScript(function (callback) {
var imgs = document.getElementsByTagName('img'),
loaded = 0;
for (var i = 0; i < imgs.length; i++) {
if (imgs[i].naturalWidth > 0) {
loaded = loaded + 1;
};
};
callback(imgs.length - loaded);
}).then(function (brokenImagesCount) {
expect(brokenImagesCount).toBe(0);
});
});
The function executed within the browser returns the number of non-loaded images.
Just an updated version of the previous answer - test is made to fail if there are broken images, because we expect 0
it('should check if there are broken images', function () {
browser.executeAsyncScript(function (callback: (arg0: number) => void) {
const imgs = document.getElementsByTagName("img");
let loaded = 0;
for (let i = 0; i < imgs.length; i++) {
if (imgs[i].naturalWidth > 0) {
loaded = loaded + 1;
}
}
callback(imgs.length - loaded);
})
.then(function (brokenImagesCount) {
expect(brokenImagesCount).toBe(0);
});
});