Selenium Webdriver (node.js) take screenshot and s

2020-02-08 06:00发布

I started developing tests for a website application and I have some problems.

I'm using Node.js, webdriver, chromedriver and selenium rc.

The questions are: 1. How do I make a screenshot and save it in the same folder as the script. 2. Is there a way to save the test logs for a test case? For example, if check for an element on the page and don't find it, how do I output that?

3条回答
够拽才男人
2楼-- · 2020-02-08 06:06

Just for the record, this is how you take a screenshot with WebdriverJS:

var webdriverjs = require('webdriverjs'),
    client = webdriverjs.remote({
        desiredCapabilities: {
            browserName: 'chrome'
        }
    });

client
    .init()
    .url('http://google.com')
    .saveScreenshot(__dirname + '/googleScreenshot.png')
    .end();

You can also use WebdriverCSS to take screenshots. It is a plugin for WebdriverJS to do CSS regression tests. It is pretty much the same like PhantomCSS.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-02-08 06:12

Adapting aychedee's answer into a complete promise that will resolve after the file is written and reject on write failure:

const util = require('util')
const fs = require('fs')
const writeFile = util.promisify(fs.writeFile)

function takeScreenshot(driver, file){
  return driver.takeScreenshot()
    .then(image => writeFile(file, image, 'base64'))
}

Or in an async function

async function takeScreenshot(driver, file){
  let image = await driver.takeScreenshot()
  await writeFile(file, image, 'base64')
}
查看更多
闹够了就滚
4楼-- · 2020-02-08 06:15

For saving the test logs you typically use a test runner. When you check if an element is on the page and you can't find it then you raise an exception (typically an assertion error) and the test runner will record this and mark it as a failed test. In the documentation they suggest you use Mocha.

As for saving a screenshot to disk, the the api looks like this

driver.takeScreenshot().then(
    function(image, err) {
        require('fs').writeFile('out.png', image, 'base64', function(err) {
            console.log(err);
        });
    }
);
查看更多
登录 后发表回答