From caf35f884f287b8a275d895c58ebb3de4c55b8f7 Mon Sep 17 00:00:00 2001 From: wsw0108 Date: Wed, 12 Jan 2022 10:47:34 +0800 Subject: [PATCH] simple method From https://github.com/microsoft/playwright/issues/8278#issuecomment-1009957411 --- index.js | 37 ++++++++++++++++--------------------- preload.js | 39 --------------------------------------- 2 files changed, 16 insertions(+), 60 deletions(-) delete mode 100644 preload.js diff --git a/index.js b/index.js index 214b144..3ca3877 100644 --- a/index.js +++ b/index.js @@ -1,25 +1,20 @@ -const path = require('path'); - -function launch(_electron, options) { - options = options || {}; - options.args = options.args || []; - options.args.unshift(path.join(__dirname, 'preload.js')); - options.args.unshift('--require'); - return _electron.launch(options); -} - -function ipcRendererSendSyncAsync(page, message, ...args) { - return page.evaluate( - ({ message, args }) => { - const { ipcRenderer } = require('electron'); - return ipcRenderer.sendSync(message, ...args); +function mock(electronApp, options) { + // idea from https://github.com/microsoft/playwright/issues/8278#issuecomment-1009957411 by MikeJerred + return electronApp.evaluate( + ({ dialog }, options) => { + options.forEach(v => { + if (!dialog[v.method]) { + throw new Error(`can't find ${v.method} on dialog module.`) + } + if (v.method.endsWith('Sync')) { + dialog[v.method] = () => v.value; + } else { + dialog[v.method] = Promise.resolve(v.value); + } + }); }, - { message, args } + options ); } -function mock(page, options) { - return ipcRendererSendSyncAsync(page, 'PLAYWRIGHT_FAKE_DIALOG/SEND', options); -} - -module.exports = { launch, mock }; +module.exports = { mock }; diff --git a/preload.js b/preload.js deleted file mode 100644 index a4c06c0..0000000 --- a/preload.js +++ /dev/null @@ -1,39 +0,0 @@ -const { dialog, ipcMain, BrowserWindow } = require('electron'); - -const parseArgs = function (window, options, callback, ...args) { - if (window != null && window.constructor !== BrowserWindow) { - [callback, options, window] = [options, window, null] - } - if ((callback == null) && typeof options === 'function') { - [callback, options] = [options, null] - } - const lastArgument = args[args.length - 1] - if ((callback == null) && typeof lastArgument === 'function') { - callback = lastArgument - } - return [window, options, callback] -} - -function mockFunction(value, ...args) { - const [ window, options, callback ] = parseArgs(...args); - if (callback) { - setTimeout(() => callback(value), 0); - return; - } - return value; -} - -function fake(options) { - options.forEach(v => { - if (dialog[v.method]) { - dialog[v.method] = mockFunction.bind(null, v.value); - } else { - throw new Error(`can't find ${v.method} on dialog module.`); - } - }); -} - -ipcMain.on('PLAYWRIGHT_FAKE_DIALOG/SEND', (e, options) => { - fake(options); - e.returnValue = true; -});