在PhantomJS 2中运行测试时从Karma截取屏幕截图?

Fez*_*sta 8 javascript screenshot qunit phantomjs karma-runner

我需要一种在测试过程中截取屏幕截图的方法,该测试使用QUnit和Karma在PhantomJS 2.0.1中运行

我找到了这个命令:

window.top.callPhantom('render');
Run Code Online (Sandbox Code Playgroud)

这不会引发任何错误,但似乎不起作用,或者至少,我不知道在哪里寻找截图.

任何线索?

Fez*_*sta 14

找到了办法!

我必须编辑我的自定义PhantomJS自定义启动器添加一个选项:

PhantomJSCustom: {
    base: 'PhantomJS',
    options: {
        onCallback: function(data){
            if (data.type === "render") {
                // this function will not have the scope of karma.conf.js so we must define any global variable inside it
                if (window.renderId === undefined) { window.renderId = 0; }
                page.render(data.fname || ("screenshot_" + (window.renderId++) + ".png"));
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我们正在定义该onCallback选项,它将被注入到由启动的脚本中phantomjs.然后,该脚本将包含:

page.onCallback = <our function>
Run Code Online (Sandbox Code Playgroud)

现在,我们可以使用callPhantomPhantomJS来运行我们onCallback函数的内容并使用所有原生的PhantomJS方法.

用法

现在,您可以在测试中使用该功能:

window.top.callPhantom({type: 'render'});
Run Code Online (Sandbox Code Playgroud)

截取将保存在应用程序根目录中的屏幕截图.

此外,如果您定义了fname您将能够为屏幕截图定义自定义路径和文件名.

window.top.callPhantom({type: 'render', fname: '/tmp/myscreen.png'});
Run Code Online (Sandbox Code Playgroud)

将所有包装在一起以方便使用

我已经在我的测试中创建了一个方便的函数.onCallback函数减少到必要的最小值,这样所有逻辑都在我的测试环境中管理:

karma.conf.js

PhantomJSCustom: {
    base: 'PhantomJS',
    options: {
        onCallback: function(data){
            if (data.type === 'render' && data.fname !== undefined) {
                page.render(data.fname);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

帮手

// With this function you can take screenshots in PhantomJS!
// by default, screenshots will be saved in .tmp/screenshots/ folder with a progressive name (n.png)
var renderId = 0;
function takeScreenshot(file) {
    // check if we are in PhantomJS
    if (window.top.callPhantom === undefined) return;

    var options = {type: 'render'};
    // if the file argument is defined, we'll save the file in the path defined eg: `fname: '/tmp/myscreen.png'
    // otherwise we'll save it in the default directory with a progressive name
    options.fname = file || '.tmp/screenshots/' + (renderId++) + '.png';

    // this calls the onCallback function of PhantomJS, the type: 'render' will trigger the screenshot script
    window.top.callPhantom(options);
}
Run Code Online (Sandbox Code Playgroud)

积分

我从这个答案中得到了这个剧本,对它进行了调整,并在我自己发现的地方把它与业力结合起来.