我需要一种在使用 QUnit 和 Karma 在 PhantomJS 2.0.1 中运行的测试期间截屏的方法
我找到了这个命令:
window.top.callPhantom('render');
这不会引发任何错误,但似乎不起作用,或者至少,我不知道在哪里可以找到截取的屏幕截图。
有什么线索吗?
最佳答案
找到方法了!
解决方案
我不得不编辑我的自定义 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"));
}
}
}
}
如您所见,我们正在定义 onCallback
选项,它将被注入(inject)到 phantomjs
启动的脚本中。
然后,该脚本将包含:
page.onCallback = <our function>
现在,我们可以使用 callPhantom
要求 PhantomJS 运行我们的 onCallback
函数的内容,并使用所有原生的 PhantomJS 方法。
用法
现在,您可以在测试中使用函数:
window.top.callPhantom({type: 'render'});
截取将保存在应用程序根目录中的屏幕截图。
此外,如果您定义 fname
,您将能够为您的屏幕截图定义自定义路径和文件名。
window.top.callPhantom({type: 'render', fname: '/tmp/myscreen.png'});
打包在一起以便于使用
我已经创建了一个方便的函数来在我的测试中使用。 onCallback 函数被减少到最低限度,这样所有逻辑都在我的测试环境中进行管理:
karma .conf.js
PhantomJSCustom: {
base: 'PhantomJS',
options: {
onCallback: function(data){
if (data.type === 'render' && data.fname !== undefined) {
page.render(data.fname);
}
}
}
}
助手
// 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);
}
致谢
我从 this answer 得到了这个脚本, 对其进行了调整,并自己找到了将其放置在何处以使其与 karma 一起工作。
关于javascript - 在 PhantomJS 2 中运行测试时从 Karma 截取屏幕截图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34694765/