Found a way!
Decision
I had to edit the PhantomJS custom launcher by adding an option:
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")); } } } }
As you can see, we define the onCallback option, it will be introduced inside the script launched by phantomjs . Then the script will contain:
page.onCallback = <our function>
Now we can use callPhantom to ask PhantomJS to run the contents of our onCallback function and use all PhantomJS native methods.
Using
Now you can use the function in your tests:
window.top.callPhantom({type: 'render'});
Take a screenshot to be saved in the root directory of your application.
In addition, if you specify fname , you can determine your own path and file name in the screenshot.
window.top.callPhantom({type: 'render', fname: '/tmp/myscreen.png'});
Pack it all together for ease of use
I created a convenient function to use inside my tests. The onCallback function is reduced to the minimum necessary, thus, all the logic is controlled inside my test environment:
karma.conf.js
PhantomJSCustom: { base: 'PhantomJS', options: { onCallback: function(data){ if (data.type === 'render' && data.fname !== undefined) { page.render(data.fname); } } } }
assistant
// 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); }
Loans
I got this script from this answer , adapted it and found myself where it can be made to work with karma.