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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With