How to mock require in electronJS - javascript

I'm trying to write unit test for my electron js application and I'm stuck at one place.
For example
Lets say my app code is like below
var app= (function () {
function app() {
var _this = this;
this.open = function (data) {
var deferred = Q.defer();
try {
// some code
}
catch (ex) {
deferred.reject(ex);
}
return deferred.promise;
};
}
}());
exports.app = app
Now if I want to run it on electron client it will run perfectly fine as electron module is installed on client's PC
The problem is when I'm trying to write unit test cases for the above as electron is not installed here on dev machine like below
import { app} from '../../app'
import { Rights } from '../../Rights'
describe('app', () => {
let app: app;
beforeEach(() => {
app= new app();
})
it('should call open() and return error for null content', function (done) {
let output = app.open(null);
output
.then((res) => {
//expectation
done();
})
.catch((err)=>{
//expectation
done();
})
})
})
Getting following error
Error: Cannot find module 'electron'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (<project pat>/app.js:2:16)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
npm ERR! Test failed. See above for more details.
Question
How to mock require for any module which is not installed on dev PC
but required for actual execution(installed on client's PC).

You can intercept require calls by overriding module._load :
const m = require('module');
const originalLoader = m._load;
const stubs = { electron : {} };
m._load = function hookedLoader(request, parent, isMain) {
const stub = stubs[request];
return stub || originalLoader(request, parent, isMain);
};

I have had similar issue with mocha. My basic approach was to:
* require electron in before hook,
* override it with local default
* require app
* clean in after hook
Here's a sample:
var el = require('../../modules/electron');
describe('app', function () {
'use strict';
var el_override = {
post: function () {
},
get: function () {
}
}, app;
before(function () {
/* Since we already have electron required, we override it
from node cache by:
require.cache['/path/to/file/name'].exports = el_override
*/
// Require app
// This will import overridden electron
App = require('app-location');
});
beforeEach(function () {
// init app
app = new App();
});
after(function () {
// Clean Up both electron override and app by
// delete requre.cache['/path/to/file/names']
});
it('should test for batch', function () {
// Call you functions
});
});

Related

VUE JS 3 TypeError: vue.initDirectivesForSSR is not a function

I've tried to build my vue web app using this config, but I got these errors, I've tried this issue but I can't found someone got the same issue as me. How can I deal with this issue, by the way the build succeeded, the issues happened when I tried to run node src/server.jsx? Thanks in advance
$ node src/server.jsx
D:\myPathProject\node_modules\#vue\server-renderer\dist\server-renderer.cjs.js:994
vue.initDirectivesForSSR();
^
TypeError: vue.initDirectivesForSSR is not a function
at Object.<anonymous> (D:\myPathProject\node_modules\#vue\server-renderer\dist\server
-renderer.cjs.js:994:5)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Module.require (internal/modules/cjs/loader.js:961:19)
at require (internal/modules/cjs/helpers.js:92:18)
at Object.<anonymous> (D:\myPathProject\node_modules\#vue\server-renderer\index.js:6:
20)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
this is my vue.config.js file
/* eslint-disable #typescript-eslint/no-var-requires */
const { WebpackManifestPlugin } = require("webpack-manifest-plugin")
const nodeExternals = require("webpack-node-externals")
exports.chainWebpack = (webpackConfig) => {
if (!process.env.VUE_APP_SSR) return
webpackConfig
.entry("app")
.clear()
.add("./src/main.server.ts")
webpackConfig.target("node")
webpackConfig.output.libraryTarget("commonjs2")
webpackConfig
.plugin("manifest")
.use(new WebpackManifestPlugin({ fileName: "ssr-manifest.json" }))
webpackConfig.externals(nodeExternals({ allowlist: /\.(css|vue)$/ }))
webpackConfig.optimization.splitChunks(false).minimize(false)
webpackConfig.plugins.delete("hmr")
webpackConfig.plugins.delete("preload")
webpackConfig.plugins.delete("prefetch")
webpackConfig.plugins.delete("progress")
webpackConfig.plugins.delete("friendly-errors")
}
and this is my server.jsx file
/* eslint-disable #typescript-eslint/no-var-requires */
const express = require("express")
const path = require("path")
const { createSSRApp } = require("vue")
const { renderToString } = require("#vue/server-renderer")
const manifest = require("../dist/ssr-manifest.json")
const server = express()
const appPath = path.join(__dirname, "../dist", manifest["app.js"])
const App = require(appPath).default
server.get("*", async (_req, res) => {
const content = createSSRApp(App)
const appContent = await renderToString(content)
const html = `
<html>
<head>
<title>Hello</title>
</head>
<body>
${appContent}
</body>
</html>
`
res.end(html)
})
server.listen(8080)
Thank you guys
Try updating your Vue 3 version.
My #vue/server-renderer package was 3.2.20 and my Vue version was 3.2.6. I bumped my Vue version to 3.2.20 and it's working great now. :)

Why export const helloWorld gives an error in firebase deploy and exports.helloWorld does not?

In a React Native project using Expo, I was trying to deploy the following cloud function using export:
Note: I use Javascript in the index.js.
export const helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
But I got this error:
Error: Error occurred while parsing your function triggers.
/Users.../functions/index.js:5
export const helloWorld = functions.https.onRequest((request, response) => {
^^^^^^
SyntaxError: Unexpected token export
at new Script (vm.js:80:7)
at createScript (vm.js:274:10)
at Object.runInThisContext (vm.js:326:10)
at Module._compile (internal/modules/cjs/loader.js:664:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
Then I used exports.helloWorld... and it worked fine!
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
Can anyone explain why this happened?
Thanks
change it to:
const helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
});
module.exports = helloWorld
direct exports make the export one of exports. ie: refer by exports.something
Module.exports assign export directly where refered.

AWS Lambda exports class not working

I am using NodeJs 6.10.2. I am using 2 files
index.js
var operation = require('./Handler/opHandler').opHandler;
var lambdaHandler = function () {
var o = new operation();
o.deleteMessage();
}
exports.lambdaHandler = function(event, context, callback) {
handleSQSMessages(context, callback);
};
opHandler.js
opHandler = function() {
this.db = '';
}
opHandler.prototype.deleteMessage = function (receiptHandle, callback) {
// My code here
// this.db = 'new val';
}
exports.opHandler = opHandler;
when run index.lambdaHandler on AWS Lambda with NodeJs 6.10, following error occurs
Syntax error in module 'index': SyntaxError
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (/var/task/index.js:16:13)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
I have googled and found similar issue here but according to it above code should work in NodeJs 6.10
Try another method or module export. It should work in your case.
index.js
var operation = require('./Handler/opHandler');
var lambdaHandler = function () {
var o = new operation();
o.deleteMessage();
}
exports.lambdaHandler = function(event, context, callback) {
handleSQSMessages(context, callback);
};
opHandler.js
opHandler = function() {
this.db = '';
}
opHandler.prototype.deleteMessage = function (receiptHandle, callback) {
// My code here
// this.db = 'new val';
}
module.exports = opHandler;
It solved my issue may help you out.

TypeError: object is not a function In Node JS / socket.io

I am very new with MEAN stack. I am facing "TypeError: object is not a function" while starting my server > node index.js.
.../master/server/app.js:47
require('./config/socketio')(socketio);
^
TypeError: object is not a function
at Object.<anonymous> (/home/divine20/master/server/app.js:30:2)
at Module._compile (module.js:456:26)
at loader (/home/divine20/master/node_modules/babel-core/node_modules/babel-register/lib/node.js:146:5)
at Object.require.extensions.(anonymous function) [as .js] (/home/divine20/master/node_modules/babel-core/node_modules/babel-register/lib/node.js:156:7)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/home/divine20/master/server/index.js:12:28)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
My Index.js file is
'use strict';
// Set default node environment to development
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
if (env === 'development' || env === 'test') {
// Register the Babel require hook
require('babel-core/register');
}
// Export the application
exports = module.exports = require('./app');
App.js File
/**
* Main application file
*/
'use strict';
import express from 'express';
import mongoose from 'mongoose';
mongoose.Promise = require('bluebird');
import config from './config/environment';
import http from 'http';
// Connect to MongoDB
mongoose.connect(config.mongo.uri, config.mongo.options);
mongoose.connection.on('error', function(err) {
console.error('MongoDB connection error: ' + err);
process.exit(-1);
});
// Populate databases with sample data
if (config.seedDB) { require('./config/seed'); }
// Setup server
var app = express();
var server = http.createServer(app);
var socketio = require('socket.io')(server, {
serveClient: config.env !== 'production',
path: '/socket.io-client'
});
require('./config/socketio')(socketio);
require('./config/express')(app);
require('./routes')(app);
// Start server
function startServer() {
app.angularFullstack = server.listen(config.port, config.ip, function() {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
}
setImmediate(startServer);
// Expose app
exports = module.exports = app;
// Socketio.js
/**
* Socket.io configuration
*/
'use strict';
import config from './environment';
// When the user disconnects.. perform this
function onDisconnect(socket) {
}
// When the user connects.. perform this
function onConnect(socket) {
// When the client emits 'info', this listens and executes
socket.on('info', data => {
socket.log(JSON.stringify(data, null, 2));
});
// Insert sockets below
require('../api/utility/utility.socket').register(socket);
require('../api/repayment/repayment.socket').register(socket);
require('../api/transaction/transaction.socket').register(socket);
require('../api/offer/offer.socket').register(socket);
require('../api/payment/payment.socket').register(socket);
require('../api/yelp/yelp.socket').register(socket);
require('../api/faq/faq.socket').register(socket);
require('../api/blog/blog.socket').register(socket);
require('../api/user/user.socket').register(socket);
//require('../api/listing/listing.socket').register(socket);
}
export default function(socketio) {
// socket.io (v1.x.x) is powered by debug.
// In order to see all the debug output, set DEBUG (in server/config/local.env.js) to including the desired scope.
//
// ex: DEBUG: "http*,socket.io:socket"
// We can authenticate socket.io users and access their token through socket.decoded_token
//
// 1. You will need to send the token in `client/components/socket/socket.service.js`
//
// 2. Require authentication here:
// socketio.use(require('socketio-jwt').authorize({
// secret: config.secrets.session,
// handshake: true
// }));
socketio.on('connection', function(socket) {
socket.setMaxListeners(20);
socket.address = socket.request.connection.remoteAddress +
':' + socket.request.connection.remotePort;
socket.connectedAt = new Date();
socket.log = function(...data) {
console.log(`SocketIO ${socket.nsp.name} [${socket.address}]`, ...data);
};
// Call onDisconnect.
socket.on('disconnect', () => {
onDisconnect(socket);
socket.log('DISCONNECTED');
});
// Call onConnect.
onConnect(socket);
socket.log('CONNECTED');
});
}
Thanks in advance.
You're using a default export. It's likely that whatever you're using to compile your code (e.g. Babel or TypeScript) emits a default export by adding a property onto module.exports named default.
Try to write write require('./config/socketio').default(socketio).

SyntaxError: Unexpected token using async and babel in koa

I have this simple app made using the last alpha version of Koa. In order to use `async/wait Babel.Js is required.
'use strict';
// babel registration (runtime transpilation for node)
require('./server.babel');
const Koa = require('koa');
const app = new Koa();
// define logger - this will be always executed
const logger = async (context, next) => {
const start = new Date;
await next();
const ms = new Date - start;
console.log(`${context.method} ${context.url} - ${ms}ms`);
}
const index = (context) => {
context.body = 'Hello World';
}
app.use(logger);
app.use(index);
app.listen(3000);
console.info(`The app is listening on port 3000`);
This is the hook to activate the transpiling.
const fs = require('fs');
let config;
try {
config = JSON.parse(fs.readFileSync('./.babelrc'));
} catch (error) {
console.error('==> ERROR: Error parsing your .babelrc.');
console.error(error);
}
require('babel-core/register')(config);
and this is the config file:
{
"plugins": ["transform-async-to-generator"]
}
Unfortunately when I try to run the project I get the following error:
const logger = async (context, next) => {
^
SyntaxError: Unexpected token (
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:404:25)
at Object.Module._extensions..js (module.js:432:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:457:10)
at startup (node.js:138:18)
at node.js:974:3
I have no idea why I get this error. I'm using the last Node.Js version 5.1.0 and Babel 6.2.1
You are getting the SyntaxError. That happens because your code is being parsed before Babel can intercept it and convert.
If you want to make async functions work in your first file, you should require this entire file after have registered its hook.
Create a new file start.js with the following
require('babel-register');
require('./index');
Your code in index.js can use async functions, but you can't do it in the start.js.
Also note, that you don't need to read .babelrc by yourself. Babel will do it for you by default.
Contents of .babelrc looks like this
{
"presets": [
"es2015",
"stage-3"
],
"plugins": [
[
"transform-runtime",
{
"polyfill": false,
"regenerator": true
}
]
]
}
Reference links
Async Functions with Babel
babel's require hook
upgrade nodejs version to v7.6.0 or higher

Categories