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

100% Statements 11/11
100% Branches 4/4
100% Functions 6/6
100% Lines 11/11

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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61                                                                6x 1x           5x 1x     4x 4x   4x 4x 1x 2x 1x                    
/**
 * Uploads a file to the Selenium Standalone server or other browser driver
 * (e.g. Chromedriver) by using the [`file`](/api/protocol/file.html) command.
 * _Note:_ that this command is only supported if you use a Selenium Hub or
 * Chromedriver directly.
 *
 * <example>
    :touchAction.js
    const path = require('path');
 
    it('should upload a file', function () {
        const filePath = path.join(__dirname, '/local/path/to/your/file');
 
        const remoteFilePath = browser.uploadFile(filePath);
        $('.upload-data-file-input').setValue(remoteFilePath);
    });
 * </example>
 *
 * @alias browser.uploadFile
 * @param {String} localPath local path to file
 * @type utility
 * @uses protocol/file
 *
 */
import fs from 'fs'
import path from 'path'
import archiver from 'archiver'
 
export default async function uploadFile (localPath) {
    /**
     * parameter check
     */
    if (typeof localPath !== 'string') {
        throw new Error('number or type of arguments don\'t agree with uploadFile command')
    }
 
    /**
     * check if command is available
     */
    if (typeof this.file !== 'function') {
        throw new Error(`The uploadFile command is not available in ${this.capabilities.browserName}`)
    }
 
    let zipData = []
    let source = fs.createReadStream(localPath)
 
    return new Promise((resolve, reject) => {
        archiver('zip')
            .on('error', (err) => reject(err))
            .on('data', (data) => zipData.push(data))
            .on('end', () => this.file(Buffer.concat(zipData).toString('base64')).then(resolve, reject))
            .append(source, { name: path.basename(localPath) })
            .finalize((err) => {
                /* istanbul ignore next */
                if (err) {
                    reject(err)
                }
            })
    })
}