找到方法了!
解决方案
我必须编辑我的自定义 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 选项,它将被注入到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 一起使用。