export default function (path = '' /*, query = {}*/) { const location = url.resolve(BASE_URL, path); /* add custom actions here */ nightmare.action('touchTap', function(selector, done) { this.evaluate_now((selector) => { const t = new Touch({ identifier: Date.now(), target: document.querySelector(selector), clientX: 100, clientY: 100, radiusX: 2.5, radiusY: 2.5, rotationAngle: 10, force: 0.5, }); const touchEvent = new TouchEvent('touchend', { cancelable: true, bubbles: true, touches: [t], targetTouches: [], changedTouches: [t], shiftKey: true, }); document.querySelector(selector).dispatchEvent(touchEvent); }, done, selector); }); /* Create new nightmare instance */ const page = nightmare({ show: true, pollInterval: 50, }).viewport(1260, 700); return page.goto(location); }
Nightmare.action('screenshotSelector', function (path, selector, done) { console.log('.screenshotSelector()'); if (typeof selector === 'function') { done = selector; selector = path; path = undefined; }; var self = this; this.evaluate_now(function (selector) { var element = document.querySelector(selector); if (element) { var rect = element.getBoundingClientRect(); return { x: Math.round(rect.left), y: Math.round(rect.top), width: Math.round(rect.width), height: Math.round(rect.height) }; } }, function (a, clip) { if (!clip) { throw new Error('invalid selector "' + selector + '"'); } console.log('width:'+clip.width+" height:"+clip.height) self.child.call('screenshot', path, clip, function (error, img) { var buf = new Buffer(img.data); console.log('.screenshot() captured with length %s', buf.length); path ? fs.writeFile(path, buf, done) : done(null, buf); }); //not work with nightmare 2.5.1 // self.child.once('screenshot', function (img) { // var buf = new Buffer(img.data); // console.log('.screenshotSelector() captured with length %s', buf.length); // path ? fs.writeFile(path, buf, done) : done(null, buf); // }); // self.child.emit.('screenshot', path, clip); }, selector); })
'use strict' const assert = require('assert') const process = require('process') const Nightmare = require('nightmare') const pixelmatch = require('pixelmatch') require('nightmare-load-filter')(Nightmare) Nightmare.action('getClipboard', function(name, options, parent, win, renderer, done) { const {clipboard} = require('electron') parent.respondTo('getClipboard', function(done) { const text = clipboard.readText() done(null, text) }) done() }, function(done) { this.child.call('getClipboard', done) } ) Nightmare.action('clearClipboard', function(name, options, parent, win, renderer, done) { const {clipboard} = require('electron') parent.respondTo('clearClipboard', function(done) { clipboard.writeText('') done() }) done()
'use strict'; const fs = require('fs-extra'); const Nightmare = require('nightmare'); const screenshotSelector = require('nightmare-screenshot-selector'); const path = require('path'); const PropertiesReader = require('properties-reader'); const util = require('./util.js'); Nightmare.action('screenshotSelector', screenshotSelector); async function main(argv) { const script = require(argv[2]); const nightmare = Nightmare(script.nightmare_props); let atlasLoginInfo = {}; let chartsLoginInfo = {}; if (argv[3] !== undefined) { const properties = PropertiesReader(argv[3]); atlasLoginInfo = { username: properties.get('atlasUser.login.username'), password: properties.get('atlasUser.login.password') } chartsLoginInfo = { email: properties.get('chartsUser.login.email'), password: properties.get('chartsUser.login.password') } } const screenshotNames = await script.run({ nightmare: nightmare,
var Nightmare = require('nightmare'), fn = require('./webrequest-callback-factory')('onBeforeRedirect') Nightmare.action('onBeforeRedirect', function (name, options, parent, win, renderer, done) { parent.on('onBeforeRedirect', function () { var args = [] !!arguments[0] && args.push(arguments[0]) var arg1 = args.length ? args.pop() : null if (typeof arg1 === 'object') { win.webContents.session.webRequest.onBeforeRedirect(arg1, function (details) { parent.emit('onBeforeRedirect', details) }) } else { win.webContents.session.webRequest.onBeforeRedirect(null) } parent.emit('onBeforeRedirect') }) done() return this }, fn)
Nightmare.action('ug', { 'log': function(message, done) { winston.info(`>>> ${message}`); done(); }, 'commit': function(commitMessage, done) { this.wait('.files .file .btn-default') .insert('.staging input.form-control', commitMessage) .wait(100) .ug.click('.commit-btn') .ug.waitForElementNotVisible('.files .file .btn-default') .wait(1000) .then(done.bind(null, null), done); }, 'commitnpush': function(commitMessage, done) { this.wait('.files .file .btn-default') .insert('.staging input.form-control', commitMessage) .ug.click('.commit-grp .dropdown-toggle') .ug.click('.commitnpush') .then(done.bind(null, null), done); }, 'amendCommit': function(done) { this.ug.click('.amend-link') .ug.click('.commit-btn') .ug.waitForElementNotVisible('.files .file .btn-default') .wait(1000) .then(done.bind(null, null), done); }, 'emptyCommit': function(done) { this.ug.click('.empty-commit-link') .ug.click('.commit-btn') .ug.waitForElementNotVisible('.files .file .btn-default') .wait(1000) .then(done.bind(null, null), done); }, 'checkout': function(branch, done) { this.ug.click(`.branch[data-ta-name="${branch}"]`) .ug.click('[data-ta-action="checkout"]:not([style*="display: none"]) .dropmask') .wait(`.ref.branch[data-ta-name="${branch}"].current`) .then(done.bind(null, null), done); }, 'patch': function(commitMessage, done) { this.ug.click('.files .file .btn-default') .ug.click('.patch') .wait('.d2h-diff-tbody input') .ug.commit(commitMessage) .then(done.bind(null, null), done); }, 'backgroundAction': function(method, url, body, done) { let req; if (method === 'GET') { req = request.get(url).withCredentials().query(body); } else if (method === 'POST') { req = request.post(url).send(body); } else if (method === 'DELETE') { req = request.delete(url).send(body); } req.set({'encoding': 'utf8', 'cache-control': 'no-cache', 'Content-Type': 'application/json'}); req.end((err, res) => { let data = (res || {}).body try { data = JSON.parse(data); } catch(ex) {} done(err, data) }); }, 'createTestFile': function(filename, done) { this.ug.backgroundAction('POST', `${rootUrl}/api/testing/createfile`, { file: filename }) .then(done.bind(null, null), done); }, 'shutdownServer': function(done) { this.ug.backgroundAction('POST', `${rootUrl}/api/testing/shutdown`, undefined) .then(done.bind(null, null), done); }, 'changeTestFile': function(filename, done) { this.ug.backgroundAction('POST', `${rootUrl}/api/testing/changefile`, { file: filename }) .then(done.bind(null, null), done); }, 'createTempFolder': function(done) { winston.info('Creating temp folder'); this.ug.backgroundAction('POST', `${rootUrl}/api/testing/createtempdir`, undefined) .then(done.bind(null, null), done); }, 'createFolder': function(dir, done) { winston.info(`Create folder: ${dir}`); this.ug.backgroundAction('POST', `${rootUrl}/api/createdir`, { dir: dir }) .then(done.bind(null, null), done); }, 'initRepo': function(options, done) { (options.path ? rimraf(options.path).then(() => mkdirp(options.path)) : this.ug.createTempFolder()) .then((res) => { options.path = res.path ? res.path : res; return this.ug.backgroundAction('POST', `${rootUrl}/api/init`, options) }).then(done.bind(null, null), done); }, 'gitCommand': function(options, done) { this.ug.backgroundAction('POST', `${rootUrl}/api/testing/git`, options) .then(done.bind(null, null), done); }, 'waitForElementNotVisible': function(selector, done) { this.wait((selector) => !document.querySelector(selector), selector) .then(done.bind(null, null), done); }, '_verifyRefAction': function(action, done) { this.visible('.modal-dialog .btn-primary') .then((isVisible) => { return (isVisible ? this.ug.click('.modal-dialog .btn-primary') : this) .ug.waitForElementNotVisible(`[data-ta-action="${action}"]:not([style*="display: none"])`) .wait(200) }).then(done.bind(null, null), done); }, 'refAction': function(ref, local, action, done) { this.ug.click(`.branch[data-ta-name="${ref}"][data-ta-local="${local}"]`) .ug.click(`[data-ta-action="${action}"]:not([style*="display: none"]) .dropmask`) .then(() => this.ug._verifyRefAction(action)) .then(done.bind(null, null), done); }, 'moveRef': function(ref, targetNodeCommitTitle, done) { this.ug.click(`.branch[data-ta-name="${ref}"]`) .ug.click(`[data-ta-node-title="${targetNodeCommitTitle}"] [data-ta-action="move"]:not([style*="display: none"]) .dropmask`) .then(() => this.ug._verifyRefAction('move')) .then(done.bind(null, null), done); }, '_createRef': function(type, name, done) { this.ug.click('.current ~ .newRef button.showBranchingForm') .insert('.newRef.editing input', name) .wait(100) // cannot use .ug.click as wait op will defocus and doms will disappear .click(`.newRef ${type === 'branch' ? '.btn-primary' : '.btn-default'}`) .wait(`.ref.${type}[data-ta-name="${name}"]`) .wait(300) .then(done.bind(null, null), done); }, 'createTag': function(name, done) { this.ug._createRef('tag', name).then(done.bind(null, null), done); }, 'createBranch': function(name, done) { this.ug._createRef('branch', name).then(done.bind(null, null), done); }, 'click': function(selector, done) { this.wait(selector) .wait(300) .click(selector) .wait(300) .mouseover('img.headerLogo') .wait(300) .then(done.bind(null, null), done); }, 'openUngit': function(tempDirPath, done) { this.goto(`${rootUrl}/#/repository?path=${encodeURIComponent(tempDirPath)}`) .wait('.repository-actions') .wait(1000) .then(done.bind(null, null), done); } });
Nightmare.action('onBeforeSendHeaders', function (name, options, parent, win, renderer, done) { parent.on('onBeforeSendHeaders', function () { var args = [] !!arguments[0] && args.push(arguments[0]) !!arguments[1] && args.push(arguments[1]) var arg1 = args.length ? args.pop() : null var arg2 = args.length ? args.pop() : null if (typeof arg1 === 'object' && arg2) { win.webContents.session.webRequest.onBeforeSendHeaders(arg1, function (details, cb) { parent.emit('onBeforeSendHeaders', details) var fn = new Function('with(this){return ' + arg2 + '}').call({}) return fn(details, cb) }) } else if (arg1) { win.webContents.session.webRequest.onBeforeSendHeaders(function (details, cb) { parent.emit('onBeforeSendHeaders', details) var fn = new Function('with(this){return ' + arg1 + '}').call({}) return fn(details, cb) }) } else { win.webContents.session.webRequest.onBeforeSendHeaders(null) } parent.emit('onBeforeSendHeaders') }) done() return this }, fn)
/*global Testem, arguments, __nightmare*/ 'use strict' var Nightmare = require('nightmare') require('nightmare-custom-event')(Nightmare) Nightmare.action('sendImage', function (ns, options, parent, win, renderer, done) { parent.respondTo('sendImage', function (image, done) { win.webContents.send('return-image-event', { image: image }).catch(function (error) { console.error('error-send-image', error) }) done() }) done() }, function (image, done) { this.child.call('sendImage', image, done) }) var nightmare = Nightmare( // { // openDevTools: { // mode: 'detach' // }, // show: true // } ) var url = process.argv[2] nightmare
// TODO :: https://github.com/segmentio/nightmare/issues/782 Nightmare.action("broquire", function(id, browserValue, done) { // Avoid weird magic with `nightmare.broquire(id)` if (done === undefined) { done = browserValue; browserValue = undefined; } if (browserValue !== undefined) { this.evaluate_now( function(id, browserValue) { return window.broquire(id, browserValue); }, done, id, browserValue); } else { // This avoids `browserValue` being passed as `[null]` (due to serialization?) this.evaluate_now( function(id) { return window.broquire(id); }, done, id); } });
import assert from 'assert'; import Nightmare from 'nightmare'; import savedData from '../fixtures/localstorage'; const URI = 'http://127.0.0.1:8080/'; /** * Click an element of material-ui. * material-ui uses `mouseup` to listen user's clicks. */ Nightmare.action( 'clickMaterialUI', function clickMaterialUI(selector, done) { this.evaluate_now((sel) => { const element = document.querySelector(sel); const event = document.createEvent('MouseEvent'); event.initEvent('mouseup', true, true); element.dispatchEvent(event); }, done, selector); }, ); const n = new Nightmare({ x: 0, y: 0, show: process.env.NODE_ENV === 'development', waitTimeout: 10000, }); after(async () => { await n.evaluate(() => {