I'm using intern.js to test a web app. I can execute tests and create screenshots when they fail. I want to create a screenshot for specific element in order to do some CSS regression testing using tools like resemble.js. Is it possible? How can I do? Thank you!
Asked
Active
Viewed 554 times
2 Answers
1
driver.get("http://www.google.com");
WebElement ele = driver.findElement(By.id("hplogo"));
//Get entire page screenshot
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullImg = ImageIO.read(screenshot);
//Get the location of element on the page
Point point = ele.getLocation();
//Get width and height of the element
int eleWidth = ele.getSize().getWidth();
int eleHeight = ele.getSize().getHeight();
//Crop the entire page screenshot to get only element screenshot
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(), eleWidth,
eleHeight);
ImageIO.write(eleScreenshot, "png", screenshot);
//Copy the element screenshot to disk
File screenshotLocation = new File("C:\\images\\GoogleLogo_screenshot.png");
FileUtils.copyFile(screen, screenshotLocation);
Taken from here.
1
There isn't a built in way to do this with Intern. The takeScreenshot
method simply calls Selenium's screenshot service, which returns a screenshot of the entire page as a base-64 encoded PNG. Intern's takeScreenshot
converts this to a Node buffer before handing the result to the user.
To crop the image you will need to use an external library or tool such as png-crop (note that I've never used this). The code might look like the following (untested):
var image;
var size;
var position;
return this.remote
// ...
.takeScreenshot()
.then(function (imageBuffer) {
image = imageBuffer;
})
.findById('element')
.getSize()
.then(function (elementSize) {
size = elementSize;
})
.getPosition()
.then(function (elementPosition) {
position = elementPosition;
})
.then(function () {
// assuming you've loaded png-crop as PNGCrop
var config = {
width: size.width,
height: size.height,
top: position.y,
left: position.x
};
// need to return a Promise since PNGCrop.crop is an async method
return new Promise(function (resolve, reject) {
PNGCrop.crop(image, 'cropped.png', config, function (err) {
if (err) {
reject(err);
}
else {
resolve();
}
});
});
})

jason0x43
- 3,363
- 1
- 16
- 15
-
thank you, I'll use something like WebdriverCSS that is able to do what i need. – scosmaa Aug 23 '16 at 15:24
-
Interesting, I hadn't seen WebDriverCSS. We're actually working on a visual regression testing update for Intern, so this type of operation may become a bit easier in the future. – jason0x43 Aug 23 '16 at 18:04
-
How to import node.js module (PNGCrop) in Intern test module? – Shrike Sep 22 '16 at 13:00
-
Assuming you're writing your test modules in AMD format, and assuming that you've installed png-crop, use a dependency of `intern/dojo/node!png-crop` in your test suite. – jason0x43 Sep 22 '16 at 19:30