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
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 }); });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.