From 87830ff106f8fc3ee5acbcd496fd71225f822a74 Mon Sep 17 00:00:00 2001 From: John Knox Date: Mon, 22 Oct 2018 08:58:54 -0700 Subject: [PATCH] Add transform for stubbing electron Summary: The idea behind this is to enable tests running in pure node, without electron, because electron requires display drivers and complicated things. I've been lazy and only added the bare minimum electron api's for the connection test to pass. It would be awesome to auto generate it properly. Reviewed By: danielbuechele Differential Revision: D10238132 fbshipit-source-id: d4a2da2baf5f8964184b532a581c3a75ee33ef06 --- static/electron-stubs.notjs | 12 +++++++++++ static/transforms/electron-stubs.js | 33 +++++++++++++++++++++++++++++ static/transforms/index.js | 6 +++++- 3 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 static/electron-stubs.notjs create mode 100644 static/transforms/electron-stubs.js diff --git a/static/electron-stubs.notjs b/static/electron-stubs.notjs new file mode 100644 index 000000000..57d46bbf3 --- /dev/null +++ b/static/electron-stubs.notjs @@ -0,0 +1,12 @@ +{ + remote: { + process: { + env: {}, + }, + getCurrentWindow: function() { + return { + isFocused: function() {return true;} + }; + }, + }, +} diff --git a/static/transforms/electron-stubs.js b/static/transforms/electron-stubs.js new file mode 100644 index 000000000..d7d3c5bbf --- /dev/null +++ b/static/transforms/electron-stubs.js @@ -0,0 +1,33 @@ +/** + * Copyright 2018-present Facebook. + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * @format + */ + +var babylon = require('@babel/parser'); +var fs = require('fs'); + +var electronStubs = babylon.parseExpression( + fs.readFileSync('static/electron-stubs.notjs').toString(), +); + +module.exports = function(babel) { + return { + name: 'replace-electron-requires-with-stubs', + visitor: { + CallExpression(path) { + if ( + path.node.type === 'CallExpression' && + path.node.callee.type === 'Identifier' && + path.node.callee.name === 'require' && + path.node.arguments.length > 0 + ) { + if (path.node.arguments[0].value === 'electron') { + path.replaceWith(electronStubs); + } + } + }, + }, + }; +}; diff --git a/static/transforms/index.js b/static/transforms/index.js index 90a41a4fb..be2d0f04a 100644 --- a/static/transforms/index.js +++ b/static/transforms/index.js @@ -37,7 +37,11 @@ function transform({filename, options, src}) { require('./dynamic-requires.js'), ]; - if (!options.isTestRunner) { + if (options.isTestRunner) { + if (process.env.USE_ELECTRON_STUBS) { + plugins.push(require('./electron-stubs.js')); + } + } else { // Replacing require statements with electronRequire to prevent metro from // resolving them. electronRequire are resolved during runtime by electron. // As the tests are not bundled by metro and run in @jest-runner/electron,