Skip to content

Instantly share code, notes, and snippets.

@straris
Forked from Bunk/uploadLocalFile.js
Last active April 18, 2022 07:51
Show Gist options
  • Save straris/fc22605a16c42275253c39fc07de4fed to your computer and use it in GitHub Desktop.
Save straris/fc22605a16c42275253c39fc07de4fed to your computer and use it in GitHub Desktop.
Nightwatch — Upload local files to remote selenium grid
const path = require('path');
const util = require('util');
const events = require('events');
const archiver = require('archiver');
function uploadLocalFile() {
events.EventEmitter.call(this);
}
util.inherits(uploadLocalFile, events.EventEmitter);
/**
* uploadLocalFile is responsible for using webdriver protocol to upload a local
* file to a remote Selenium server for use in testing uploads.
*
* @argument filePath Local path to the file used for uploading
* @argument inputSelector Input selector for the file input to upload with
*/
uploadLocalFile.prototype.command = function uploadToSelenium(
filePath,
inputSelector
) {
const self = this;
const Nightwatch = this.client;
const api = this.api;
const uploadRemote = () => {
const buffers = [];
const zip = archiver('zip');
zip
.on('data', data => {
buffers.push(data);
})
.on('error', err => {
throw err;
})
.on('finish', () => {
const file = Buffer.concat(buffers).toString('base64');
api.session(session => {
const opt = {
path: `/session/${session.sessionId}/file`,
method: 'POST',
data: { file }
};
Nightwatch.transport.runProtocolAction(opt).then(result => {
if (result.status !== 0) throw new Error(result.value);
api.setValue(inputSelector, result.value, () =>
self.emit('complete')
);
});
});
});
const name = path.basename(filePath);
zip.file(filePath, { name });
zip.finalize();
};
uploadRemote();
return self;
};
module.exports = uploadLocalFile;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment