All files / webdriverio/src/commands/browser saveScreenshot.js

100% Statements 8/8
100% Branches 4/4
100% Functions 1/1
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42                                                        3x 2x     1x 1x   1x 1x 1x   1x    
/**
 *
 * Save a screenshot of the current browsing context to a PNG file on your OS. Be aware that
 * some browser drivers take screenshots of the whole document (e.g. Geckodriver with Firefox)
 * and others only of the current viewport (e.g. Chromedriver with Chrome).
 *
 * <example>
    :saveScreenshot.js
    it('should save a screenshot of the browser view', function () {
        browser.saveScreenshot('./some/path/screenshot.png');
    });
 * </example>
 *
 * @alias browser.saveScreenshot
 * @param   {String}  filepath  path to the generated image (`.png` suffix is required) relative to the execution directory
 * @return  {Buffer}            screenshot buffer
 * @type utility
 *
 */
 
import fs from 'fs'
import { Buffer } from 'safe-buffer'
import { getAbsoluteFilepath, assertDirectoryExists } from '../../utils'
 
export default async function saveScreenshot (filepath) {
    /**
     * type check
     */
    if (typeof filepath !== 'string' || !filepath.endsWith('.png')) {
        throw new Error('saveScreenshot expects a filepath of type string and ".png" file ending')
    }
 
    const absoluteFilepath = getAbsoluteFilepath(filepath)
    assertDirectoryExists(absoluteFilepath)
 
    const screenBuffer = await this.takeScreenshot()
    const screenshot = Buffer.from(screenBuffer, 'base64')
    fs.writeFileSync(absoluteFilepath, screenshot)
 
    return screenshot
}