twolfson / karma-electron Goto Github PK
View Code? Open in Web Editor NEWKarma launcher and preprocessor for Electron
License: The Unlicense
Karma launcher and preprocessor for Electron
License: The Unlicense
Hey @twolfson, I'm wondering if its possible to set breakpoints in tests with this launcher. I've tried jigging electron-launcher.js
to show the browser window and open dev tools and ran karma with the --debug
flag, but it doesnt seem to work like the regular chrome launcher.
Do you have any ideas/insight that could help me? The ability to set breakpoints in these tests would be wonderful.
Full stacktrace:
Uncaught TypeError: Function.prototype.toString is not generic
at http://localhost:9876/context.js:23
In context.js file I console.info()
that function name and it shows electron
's internal remoteMemberFunction
function.
In my app I use electron
's remote.require('moduleName')
several times. I think it may be important cause remoteMemberFunction
is defined in electron
's renderer/api/remote.js
file.
I start karma via karma start
. After replacing return obj.toString().replace(/\{[\s\S]*\}/, '{ ... }')
line in content.js with return;
karma seems to work fine (this is my temporal decision of solving problem).
Here is my karma.conf:
module.exports = function(config) {
config.set({
basePath: './',
frameworks: ['jasmine'],
files: [
'app/app.js', // this is a webpack app bundle with angular.js
'node_modules/angular-mocks/angular-mocks.js',
'src/**/*.html',
'src/**/*spec.js'
],
client: {
useIframe: false
},
exclude: [
'src/node_modules/**/*spec.js',
'src/node_modules/**/*.html''
],
preprocessors: {
'src/**/*.html': ['ng-html2js'],
'app/app.js': ['electron']
},
ngHtml2JsPreprocessor: {
stripPrefix: 'src/',
moduleName: 'appTemplates'
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
singleRun: false,
concurrency: Infinity,
browsers: ['Electron'],
plugins: [
'karma-electron',
'karma-jasmine',
'karma-ng-html2js-preprocessor'
]
});
};
Thank you in advance!
Hello,
In the main process of my app I have a global variable:
const navigator = require('./navigator.js');
.
.
app.on('ready', function() {
//Setup global references
global.navigator = navigator;
In my render process in index.html I use:
const navigator = remote.getGlobal('navigator');
I am trying to bootstrap the global variable so that I can test my page in karma-electron, but since it runs in the render process I am struggling. Can you suggest a strategy for injecting a global variable into the launcher from my test?
Thank you.
I'm trying to add some tests for ARK desktop wallet. In this project, the Angular.js app is requiring Node.js modules (on package.json), so using karma-electron
is a way to loading those modules.
I've changed the preprocessors
and browsers
of the Karma.js configuration, but I'm having problems:
An error "Cannot find module 'path'" is triggered from node_modules/mocha/mocha.js:1
. That files re-implements the require
function at the beginning.
any thoughts on a config switch to run tests in the main process, instead of the renderer?
nodeIntegration
is disable by default since Electron 5 because of security reasons. Could you please add a option to enable node in electron-launcher.js
or maybe allow nodeIntegration
by default?
webPreferences: {
nodeIntegration: true
}
here is the error:
Electron 1.2.1 (Node 6.1.0) ERROR
Uncaught ReferenceError: exports is not defined
at ./node_modules/jasmine-core/lib/jasmine-core/jasmine.js:32
electron has module.exports, but exports is undefined.
how should I solve this error? Thanks
Using the latest version of karma-electron
, I was hoping all the tests would be run in a full render process. However the following test:
describe('test setup', () => {
it('running in render process', () => {
expect(process.type).toEqual('renderer');
});
});
Fails with ReferenceError: process is not defined
Here is the full output:
06 03 2017 22:41:11.969:INFO [karma]: Karma v1.4.1 server started at http://0.0.0.0:9876/
06 03 2017 22:41:11.972:INFO [launcher]: Launching browser Electron with unlimited concurrency
06 03 2017 22:41:11.987:INFO [launcher]: Starting browser Electron
06 03 2017 22:41:13.777:INFO [Electron 1.4.14 (Node 6.5.0)]: Connected on socket g4QgvpKmHdzrxJwpAAAA with id 87957279
Electron 1.4.14 (Node 6.5.0) ERROR: TypeError{}
Electron 1.4.14 (Node 6.5.0) test setup running in render process FAILED
ReferenceError: process is not defined
at Object.eval (src/test/test.spec.ts!transpiled:20:28)
Electron 1.4.14 (Node 6.5.0): Executed 1 of 1 (1 FAILED) (0.048 secs / 0.039 secs)
error Command failed with exit code 1.
I can see an electron process spawning up and closing after.
Hi there! Awesome project!
I am having issues making the launcher run and it looks like it is because my Karma version was older than the required one.
I looked into this Karma PR and it seems that karma-electron
requires Karma at least 1.1.0
, is that so?
If that is correct, should we add it as a peerDependency
? I can prepare a PR.
Hi,
would it be possible to add source map support?
Played around for a while and got a working version. Don't know if it fits every edge case.
https://github.com/otbe/karma-electron/tree/source-map-support
Thanks.
I have an Electron app with Webpack, Typescript and Karma support (karma part WIP).
Originally when run it only shows the karma electron browser in launch bar, and the test output in the terminal, so far so good.
But when i use the client
's useIframe: false
property and the --show
flag in the customLaunchers.CustomElectron
it shows 2 windows, 1 for the karma testing GUI (which is almost the same as terminal) and another white screen window.
Interesting note: The second window is always white, but when i press the Debug
button in the main karma window, a third one shows with my app in there as well as the specs logs, it would be cool if that window was the actual one shown by the flags in question.
__filenameOverride
property mentioned in (script-configuration)[https://github.com/twolfson/karma-electron#script-configuration] is meant to go side to side with the --show
flag.karma-webpack
lib doesn't compile with webpack-dev-server
.feature/Testing
branch.npm i && npm run watch:test
in terminal in the cloned repo folder.Debug
button in Karma's window to see the actual app.I wonder if karma-electron can be updated so that test files can use native import
syntax (either the browser flavor, or Node.js ESM).
I guess this is an issue similar to #27, however I double-checked the Karma configuration. I have prepared a sample repository reproducing the issue:
$ git clone https://github.com/hoefling/karma-electron-showcase
...
$ yarn install
...
$ yarn test
yarn run v1.10.1
$ npm run postinstall:electron && ng test
> [email protected] postinstall:electron /Users/hoefling/projects/private/karma-electron-showcase
> node postinstall
10% building modules 1/1 modules 0 active
START:
(node:15743) DeprecationWarning: Tapable.plugin is deprecated. Use new API on `.hooks` instead
15 10 2018 17:21:34.344:INFO [karma]: Karma v3.0.0 server started at http://0.0.0.0:9876/
15 10 2018 17:21:34.345:INFO [launcher]: Launching browser Electron with unlimited concurrency
15 10 2018 17:21:34.350:INFO [launcher]: Starting browser Electron
Finished in 0 secs / 0 secs @ 17:21:37 GMT+0200 (CEST)
✖ 「wdm」: Hash: 228257890eb55d0baf07
Version: webpack 4.8.3
Time: 6346ms
Built at: 15.10.2018 17:21:37
Asset Size Chunks Chunk Names
background.jpg 227 KiB
main.js 34.5 KiB main main
polyfills.js 514 KiB polyfills polyfills
vendor.js 7.12 MiB vendor vendor
Entrypoint main = vendor.js main.js
Entrypoint polyfills = polyfills.js
[./node_modules/@angular/compiler/fesm5/testing.js] 11.4 KiB {vendor} [built]
[./node_modules/@angular/core/fesm5/core.js] 723 KiB {vendor} [built]
[./node_modules/@angular/core/fesm5/testing.js] 47.9 KiB {vendor} [built]
[./node_modules/@angular/platform-browser-dynamic/fesm5/platform-browser-dynamic.js] 20.2 KiB {vendor} [built]
[./node_modules/@angular/platform-browser-dynamic/fesm5/testing.js] 13.3 KiB {vendor} [built]
[./node_modules/@angular/platform-browser/fesm5/testing.js] 6.24 KiB {vendor} [built]
[./node_modules/core-js/es7/reflect.js] 510 bytes {polyfills} [built]
[./node_modules/zone.js/dist/zone-testing.js] 67.4 KiB {vendor} [built]
[./node_modules/zone.js/dist/zone.js] 127 KiB {polyfills} [built]
[./src sync recursive \.spec\.ts$] ./src sync \.spec\.ts$ 250 bytes {main} [built]
[./src/app/components/home/home.component.spec.ts] 1.09 KiB {main} [optional] [built]
[./src/app/services/dummy.service.spec.ts] 690 bytes {main} [optional] [built]
[./src/polyfills-test.ts] 139 bytes {polyfills} [built]
[./src/test.ts] 656 bytes {main} [built]
[0] multi ./src/polyfills-test.ts 28 bytes {polyfills} [built]
+ 290 hidden modules
ERROR in ./src/app/services/dummy.service.ts
Module not found: Error: Can't resolve 'fs' in '/Users/hoefling/projects/private/karma-electron-showcase/src/app/services'
@ ./src/app/services/dummy.service.ts 13:9-22
@ ./src/app/services/dummy.service.spec.ts
@ ./src sync \.spec\.ts$
@ ./src/test.ts
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
So basically, when I do
import * as fs from 'fs';
class Foo {
bar() {
fs.readdirSync('/tmp');
}
}
the module is not resolved in tests. The current workaround I'm using is using window.require
:
class Foo {
bar() {
window.require('fs').readdirSync('/tmp');
}
}
What should I change in karma.conf.js
in the above example in order to be able to import fs
as usual?
When karma-electron is symlinked into a project, the upward search path for node_modules
folders may not include the application where we are running tests, therefore the tests will not be able to require
dependencies because they won't be found.
I tried running karma
with NODE_PATH=
pwd/node_modules:$NODE_PATH karma ...
in case this scenario happens (it isn't needed if karma-electron is under the project node_modules).
But this NODE_PATH
does not propagate into the Electron instance.
Do you know how to set NODE_PATH
(or something similar) for the Electron instance?
When I get errors in my test code, I often see them formatted in the console like so:
Electron 2.0.17 (Node 8.9.3) ERROR
{
"message": "Uncaught TypeError: /Users/joepea/src/trusktr+infamous/src/html/behaviors/Behavior.js: Duplicate declaration \"whenDefined\"
(This is an error on an internal node. Probably an internal error.)\nat /Users/joepea/src/trusktr+infamous/node_modules/@babel/traverse/lib/s
cope/index.js:343:7\n\nundefined",
"str": "Uncaught TypeError: /Users/joepea/src/trusktr+infamous/src/html/behaviors/Behavior.js: Duplicate declaration \"whenDefined\" (Thi
s is an error on an internal node. Probably an internal error.)\nat /Users/joepea/src/trusktr+infamous/node_modules/@babel/traverse/lib/scope
/index.js:343:7\n\nundefined"
}
I noticed that the errors are the same format regardless which karma reporter I use.
Is it karma-electron outputting them like that? If so, how can I get it to output full formatted stack traces
I thought that browserWindowOptions.show
being set to false
would hide the window. However regardless of the value, windows always appear during testing.
It's not a big deal though: on CI I use xvfb-maybe to make it "headless" regardless, but I was curious as to what the actual result of browserWindowOptions.show
should be.
Due to the breaking change beginning in Electron 9 in which allowRendererProcessReuse
is set to true
by default, specs that cover modules that use non-context aware native modules, like serialport, in the renderer will fail when using the karma-electron plugin:
Error: Loading non-context-aware native module in renderer: 'PATH_TO_PROJECT\node_modules\@serialport\bindings\build\Release\bindings.node', but app.allowRendererProcessReuse is true. See https://github.com/electron/electron/issues/18397.
at process.func [as dlopen] (electron/js2c/asar.js:140:31)
at Object.Module._extensions..node (internal/modules/cjs/loader.js:1034:18)
at Object.func [as .node] (electron/js2c/asar.js:140:31)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module._load (electron/js2c/asar.js:769:28)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at bindings PATH_TO_PROJECT\node_modules\bindings\bindings.js:112:48)
at Object.<anonymous> (PATH_TO_PROJECT\node_modules\@serialport\bindings\lib\win32.js:1:129)
Error: Cannot instantiate cyclic dependency! DatabaseService
at throwCyclicDependencyError (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:5438:1)
at R3Injector.hydrate (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11344:1)
at R3Injector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11170:1)
at injectInjectorOnly (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:801:1)
at ɵɵinject (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:805:1)
at Object.StateService_Factory [as factory] (ng:///StateService/ɵfac.js:5:40)
at R3Injector.hydrate (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11348:1)
at R3Injector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11170:1)
at NgModuleRef$1.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:23935:1)
at TestBedRender3.inject (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm2015/testing.js:1930:1)
The transitional solution to this provided by the Electron team is to set allowRendererProcessReuse
to false
until version 11 of Electron but the option to set allowRendererProcessReuse
to false
does not appear to be exposed anywhere that can be set via a CLI argument or otherwise externally.
To temporarily fix this, I added
app.allowRendererProcessReuse = false;
to lib/electron-launcher.js
and created a patch with patch-package:
diff --git a/node_modules/karma-electron/lib/electron-launcher.js b/node_modules/karma-electron/lib/electron-launcher.js
index 28e779c..ac01a5a 100644
--- a/node_modules/karma-electron/lib/electron-launcher.js
+++ b/node_modules/karma-electron/lib/electron-launcher.js
@@ -35,6 +35,10 @@ app.on('window-all-closed', function handleWindowsClosed () {
app.quit();
});
+// Allow non-context aware modules to run in renderer in Electron 9+
+// https://github.com/electron/electron/issues/18397
+app.allowRendererProcessReuse = false;
+
// Update `userData` before Electron loads
// DEV: This prevents cookies/localStorage from contaminating across apps
app.setPath('userData', program.userDataDir);
This will keep our specs working until either any non-context aware dependencies catch-up to Electron's requirements or we move the usage of all of them to Electron's main process.
Is this something that would be appropriate to implement as an option in karma-electron? If so, I can write-up a PR.
it Doesn't recognize electron-prebuilt on window, but work right on osx.
it said:
21 06 2016 11:06:54.203:ERROR [plugin]: Error during loading "c:\node_modules/karma-electron" plugin:
Unexpected token ILLEGAL
21 06 2016 11:06:54.218:ERROR [preprocess]: Can not load "electron", it is not registered!
Perhaps you are missing some plugin?
21 06 2016 11:06:54.281:INFO [karma]: Karma v0.13.22 server started at http://localhost:9876/
21 06 2016 11:06:54.281:INFO [launcher]: Launching [ 'CustomElectron' ] Infinity
21 06 2016 11:06:54.296:ERROR [karma]: Found 2 load errors
npm ERR! Test failed. See above for more details.
Here's part of my karma config:
// Port config for VSCode debugging purpose
browsers: ['ElectronDebugging'],
customLaunchers: {
ElectronDebugging: {
base: 'Electron',
flags: ['--remote-debugging-port=9333']
}
},
Here's my VSCode launch task:
{
"type": "node",
"request": "launch",
"name": "Attach karma electron",
"address": "localhost",
"port": 9333,
"diagnosticLogging": true,
"pathMapping": {
"/": "${workspaceRoot}",
"/base/": "${workspaceRoot}/"
},
// "program": "$(which npm)",
// "args": [
// "test"
// ],
// "cwd": "${workspaceRoot}",
"protocol": "inspector"
},
And here's the output of running the karma runner in watch mode, opening the debug with the button Debug
and trying to attach to such:
Help?
Tooling is always tricky business. This is what I have in my config:
browsers: ['CustomElectron'],
customLaunchers: {
CustomElectron: {
base: 'Electron',
flags: [ '--show' ]
browserWindowOptions: {
nodeIntegration: true,
nodeIntegrationInWorker: true,
nodeIntegrationInSubFrames: true,
contextIsolation: false,
},
},
},
preprocessors: {
'dist/**/*.test.js': ['electron', 'webpack', 'sourcemap'],
},
client: {
useIframe: false,
loadScriptsViaRequire: false, // true makes no difference.
},
Did I miss something in the newer karma-electron?
Hi,
I have trying many many configurations unsuccessfully. The one detailed below, throws an error when I am executing karma start
.
arma plugin is meant to be used from within Angular CLI and will not work correctly outside of it
My package.json:
"main": "main.js",
"private": true,
"scripts": {
"postinstall": "npm run postinstall:electron && npx electron-builder install-app-deps",
"postinstall:web": "node postinstall-web",
"postinstall:electron": "node postinstall",
"ng": "ng",
"start": "npm run postinstall:electron && npm-run-all -p ng:serve electron:serve",
"build": "npm run postinstall:electron && npm run electron:serve-tsc && ng build",
"build:dev": "npm run build -- -c dev",
"build:prod": "npm run build -- -c production",
"ng:serve": "ng serve",
"ng:serve:web": "npm run postinstall:web && ng serve -o",
"electron:serve-tsc": "tsc -p tsconfig-serve.json",
"electron:serve": "wait-on http-get://localhost:4200/ && npm run electron:serve-tsc && electron . --serve",
"electron:local": "npm run build:prod && electron .",
"electron:linux": "npm run build:prod && npx electron-builder build --linux",
"electron:windows": "npm run build:prod && npx electron-builder build --windows",
"electron:mac": "npm run build:prod && npx electron-builder build --mac",
"test": "npm run postinstall:web && ng test",
"e2e": "npm run postinstall:web && ng e2e"
},
"dependencies": {
"@angular/animations": "^7.1.3",
"@angular/cdk": "~7.3.7",
"@angular/material": "^7.3.7",
"@angular/platform-server": "^7.1.3",
"angular2-fontawesome": "^5.2.1",
"class-transformer": "^0.2.3",
"electron": "^7.1.9",
"electron-json-storage": "^4.1.6",
"electron-simple-updater": "^1.5.0",
"electron-window-state-manager": "^0.3.2",
"font-awesome": "^4.7.0",
"hammerjs": "^2.0.8",
"karma-electron": "^6.3.0",
"karma-electron-launcher": "^0.2.0",
"ngx-mat-select-search": "^1.8.0",
"ngx-webstorage": "^2.0.1",
"ngx-youtube-player": "^7.1.1",
"pusher-js": "^5.0.0",
"reflect-metadata": "^0.1.13",
"require-context": "^1.1.0",
"rxjs-compat": "^6.3.3",
"shelljs": "^0.8.3",
"tslib": "^1.9.0"
},
"devDependencies": {
"@angular-devkit/build-angular": "0.13.0",
"@angular/cli": "^7.1.3",
"@angular/common": "^7.1.3",
"@angular/compiler": "^7.1.3",
"@angular/compiler-cli": "^7.1.3",
"@angular/core": "^7.1.3",
"@angular/forms": "^7.1.3",
"@angular/http": "^7.1.3",
"@angular/language-service": "^7.1.3",
"@angular/platform-browser": "^7.1.3",
"@angular/platform-browser-dynamic": "^7.1.3",
"@angular/router": "^7.1.3",
"@ngx-translate/core": "10.0.1",
"@ngx-translate/http-loader": "3.0.1",
"@types/jasmine": "^3.3.8",
"@types/jasminewd2": "2.0.3",
"@types/node": "^10.14.13",
"codelyzer": "^5.0.0",
"core-js": "^2.6.1",
"electron-builder": "^21.1.5",
"electron-reload": "^1.4.1",
"jasmine-core": "^3.4.0",
"jasmine-spec-reporter": "^4.2.1",
"karma": "^4.4.1",
"karma-chrome-launcher": "^2.2.0",
"karma-cli": "^2.0.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"npm-run-all": "4.1.3",
"npx": "10.2.0",
"protractor": "^5.4.1",
"rxjs": "^6.3.3",
"rxjs-tslint": "^0.1.6",
"ts-node": "6.0.3",
"tslint": "^5.12.0",
"typescript": "3.1.6",
"wait-on": "2.1.0",
"webdriver-manager": "12.0.6",
"webpack": "^4.27.1",
"zone.js": "^0.8.26"
}
}
At project level I have this karma.config.js
module.exports = require('./src/karma.conf.js');
pointing to:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-electron'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../coverage'),
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['AngularElectron'],
singleRun: true,
customLaunchers: {
AngularElectron: {
base: 'Electron',
browserWindowOptions: {
webPreferences: {
nodeIntegration: true,
allowRunningInsecureContent: true
}
}
}
},
client: {
useIframe: false
}
});
};
It looks like current coverage reports return by karma-coverage
are weirdly minified and just have require('<the-test-file>')
. So you can't really get coverage reports.
I am unit testing IPC interactions between the renderer and main process, and need the ability to inject code into the main process. Ideally I would like a configuration option which will pass a file to be required inside electron-launcher.js
.
When switching from Electron 8 to 9, I noticed our Karma/Electron tests were now timing out despite the tests passing. It looks like something is keeping the Electron process alive even when running with singleRun: true
and autoWatch: false
.
I've created a repo with a fairly minimal reproduction of the problem. I've been able to see the issue using Node 12.18.2 on both Ubuntu 18 and MacOS.
Clone the repo:
git clone https://github.com/dpwatrous/karma-electron-repro.git
npm install
npm run test-iframe
npm run test-no-iframe
Hi,I have a very strange problem.
karma-electron Version 7.0.0 and electron V12.0.4 I used,
If I don't directly introduce methods like require,It works fine.
such as:
export default { name: 'landing-page', data() { return { path: require('path'), } } }
But just introduce it at the beginning.
such as:
<script> require('path') export default { name: 'landing-page', data() { return { // path: require('path'), } } } </script>
An error is reported when the test is performed
08 05 2021 16:50:10.794:INFO [karma]: Karma v2.0.5 server started at http://0.0.0.0:9876/ 08 05 2021 16:50:10.796:INFO [launcher]: Launching browser visibleElectron with unlimited concurrency 08 05 2021 16:50:10.800:INFO [launcher]: Starting browser Electron 08 05 2021 16:50:11.565:INFO [Electron 6.1.7 (Node 12.4.0)]: Connected on socket OKH0FmaGEa_pPhrtAAAA with id 29265082 Electron 6.1.7 (Node 12.4.0) ERROR { "message": "Uncaught ReferenceError: require is not defined\nat webpack:///external%20%22path%22:1 <- index.js:7:150137\n\nReferenceError: require is not defined\n at Object.<anonymous> (webpack:///external%20%22path%22:1 <- index.js:7:150137)\n at E (webpack:///webpack/bootstrap:789:21 <- index.js:1:7843)\n at r (webpack:///webpack/bootstrap:100:11 <- index.js:1:559)\n at Object.<anonymous> (webpack:///src/renderer/components/LandingPage.vue:33 <- index.js:7:128227)\n at E (webpack:///webpack/bootstrap:789:21 <- index.js:1:7843)\n at r (webpack:///webpack/bootstrap:100:11 <- index.js:1:559)\n at Module.<anonymous> (webpack:///src/renderer/components/LandingPage.vue?a2c6:1 <- index.js:7:124036)\n at E (webpack:///webpack/bootstrap:789:21 <- index.js:1:7843)\n at r (webpack:///webpack/bootstrap:100:11 <- index.js:1:559)\n at Module.<anonymous> (webpack:///src/renderer/components/LandingPage.vue:1 <- index.js:7:121858)", "str": "Uncaught ReferenceError: require is not defined\nat webpack:///external%20%22path%22:1 <- index.js:7:150137\n\nReferenceError: require is not defined\n at Object.<anonymous> (webpack:///external%20%22path%22:1 <- index.js:7:150137)\n at E (webpack:///webpack/bootstrap:789:21 <- index.js:1:7843)\n at r (webpack:///webpack/bootstrap:100:11 <- index.js:1:559)\n at Object.<anonymous> (webpack:///src/renderer/components/LandingPage.vue:33 <- index.js:7:128227)\n at E (webpack:///webpack/bootstrap:789:21 <- index.js:1:7843)\n at r (webpack:///webpack/bootstrap:100:11 <- index.js:1:559)\n at Module.<anonymous> (webpack:///src/renderer/components/LandingPage.vue?a2c6:1 <- index.js:7:124036)\n at E (webpack:///webpack/bootstrap:789:21 <- index.js:1:7843)\n at r (webpack:///webpack/bootstrap:100:11 <- index.js:1:559)\n at Module.<anonymous> (webpack:///src/renderer/components/LandingPage.vue:1 <- index.js:7:121858)" }
Can you help me see what the problem is?
Thank you very much.
Trying to run my unit tests headless on a linux box with electron but this doesn't let electron launch in Xvfb. :(
Hi, thanks for karma-electron.
I dont think karma-electron is reporting startup errors from electron, which would be nice to do.
One example is if libgtk2.0-0 isnt installed. When running karma from npm run
all it shows is the message Cannot start Electron
, but if you run electron on its own it will give more descriptive stack trace. libgtk2.0-0 not found
.
I would think you can redirect stderr to get this..
Karma message
ERROR [launcher]: Cannot start Electron
ERROR [launcher]: Electron failed 2 times (cannot start). Giving up.
expected
ERROR [launcher]: Cannot start Electron
ERROR [launcher]: Error from electron. libgtk2.0-0.so not found
ERROR [launcher]: Electron failed 2 times (cannot start). Giving up.
Description
If the nodeIntegration
is enabled via the workaround mentioned in #38 (comment), it seems to mess up the module paths which leads to modules not being able to be loaded from node_modules
.
Precisely, outputting the value of module.paths
in the Electron window (via devtools) gives me:
> module.paths
(2) ["C:\Dev\karma-electron-repro\testa…tron\dist\resources\default_app.asar\node_modules", "C:\Dev\karma-electron-repro\testa…node_modules\electron\dist\resources\node_modules"]
0: "C:\Dev\karma-electron-repro\testapp\node_modules\electron\dist\resources\default_app.asar\node_modules"
1: "C:\Dev\karma-electron-repro\testapp\node_modules\electron\dist\resources\node_modules"
length: 2
__proto__: Array(0)
This does not comply with the behaviour of a "directly launched" Electron which also adds the node_modules
folder of the directory it is launched from to the module search path.
Essentially, this behaviour leads to modules that are placed in node_modules
not being found.
Reproduction
npm install
require
hackfix by adding a require
line with the absolute path to the nodeIntegration enable script after https://github.com/twolfson/karma-electron/blob/master/lib/electron-launcher.js#L40-L42npm test
require('lodash')
module.paths
I'm curious to know if there's a way to run karma with karma-electron with ndb
so that I can step through code.
I've tried something like
./node_modules/.bin/ndb ./node_modules/.bin/karma start --single-run --browsers Electron ./config/karma.config.js
which opens the ndb devtools window, but nothing runs in there, there's no source files visible in there, nothing is paused, and karma simply runs everything. It's at least not pausing on karma code, though I imagine hooking into Electron might require some other steps.
Any idea how to inspect code running in karma-electron?
(I asked on SO, but no luck there after a month).
Hi,
I am trying to setup my test framework for our electron app. My Karma config looks something like this
'use strict';
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ["jasmine"],
browsers: ["Electron"],
files: [
{ pattern: '/home/rkumar/blah/blah/karma.shim.js', included: true, served: true},
{ pattern: '/home/rkumar/blah/blah//functionalTests/fse.spec.js', included: true, served: true }
],
preprocessors: {
'/home/rkumar/blah/blah//functionalTests/*.js': ['electron']
}
});
};
I've setup my ELECTRON_BIN to our electron binary, so when I so Karma start --log-level debug, my app launch's and on terminal it shows as
11 05 2016 17:58:11.426:DEBUG [plugin]: Loading karma-* from /home/rkumar/blah/blah//node_modules
11 05 2016 17:58:11.438:DEBUG [plugin]: Loading plugin /home/rkumar/blah/blah/node_modules/karma-chrome-launcher.
11 05 2016 17:58:11.467:DEBUG [plugin]: Loading plugin /home/rkumar/blah/blah/node_modules/karma-electron.
11 05 2016 17:58:11.491:DEBUG [plugin]: Loading plugin /home/rkumar/blah/blah/node_modules/karma-jasmine.
11 05 2016 17:58:11.941:DEBUG [karma]: List of files has changed, trying to execute
11 05 2016 17:58:11.942:WARN [karma]: No captured browser, open http://localhost:9876/
11 05 2016 17:58:11.964:DEBUG [watcher]: Watching "/home/rkumar/blah/blah/karma.shim.js"
11 05 2016 17:58:11.966:DEBUG [watcher]: Watching "/home/rkumar/blah/blah/spec/functionalTests/fse.spec.js"
11 05 2016 17:58:11.966:DEBUG [watcher]: Watching "/home/rkumar/blah/blah/app/src"
11 05 2016 17:58:11.978:INFO [karma]: Karma v0.13.22 server started at http://localhost:9876/
11 05 2016 17:58:11.995:INFO [launcher]: Starting browser Electron
11 05 2016 17:58:11.997:DEBUG [temp-dir]: Creating temp dir at /tmp/karma-86992553
11 05 2016 17:58:11.998:DEBUG [launcher]: /home/rkumar/blah/blah/Programming-linux-x64/Programming /home/rkumar/blah/blah/node_modules/karma-electron/lib/electron-launcher.js --user-data-dir /tmp/karma-86992553 --url http://localhost:9876/?id=86992553
I am not able to see my tests output, either in terminal or in app console window. Could you please help me here?
Thanks
I use config below
module.exports = config => {
config.set({
browsers: ['visibleElectron'],
client: {
useIframe: false
},
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' }
]
},
customLaunchers: {
'visibleElectron': {
base: 'Electron',
flags: ['--show']
}
},
frameworks: ['mocha', 'chai'],
files: ['./index.js'],
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
reporters: ['spec', 'coverage'],
singleRun: true,
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
}
})
}
when I run karma, electron come out with white screen and no error in electron console.
13 10 2018 08:49:27.981:INFO [karma]: Karma v2.0.5 server started at http://0.0.0.0:9876/
13 10 2018 08:49:27.983:INFO [launcher]: Launching browser visibleElectron with unlimited concurrency
13 10 2018 08:49:28.044:INFO [launcher]: Starting browser Electron
13 10 2018 08:50:28.051:WARN [launcher]: Electron have not captured in 60000 ms, killing.
13 10 2018 08:50:28.097:INFO [launcher]: Trying to start Electron again (1/2).
13 10 2018 08:51:28.098:WARN [launcher]: Electron have not captured in 60000 ms, killing.
13 10 2018 08:51:28.138:INFO [launcher]: Trying to start Electron again (2/2).
13 10 2018 08:52:28.146:WARN [launcher]: Electron have not captured in 60000 ms, killing.
13 10 2018 08:52:28.188:ERROR [launcher]: Electron failed 2 times (timeout). Giving up.
tried reinstall node_modules but do not help
"karma": "^2.0.2",
"karma-chai": "^0.1.0",
"karma-coverage": "^1.1.2",
"karma-electron": "^6.0.0",
"karma-mocha": "^1.3.0",
"karma-sourcemap-loader": "^0.3.7",
"karma-spec-reporter": "^0.0.32",
"karma-webpack": "^3.0.0",
When I tried to set the --show flag in karma.conf.js, the launcher open 2 electron windows instead of 1.
(1 with Karma and 1 empty)
This is my karma.conf.js
preprocessors: {
'**/*.js': ['electron'],
'**/*.spec.js': ['electron']
},
client: {
useIframe: false
},
browsers: ['CustomElectron'],
customLaunchers: {
CustomElectron: {
base: 'Electron',
flags: ['--show']
}
}
If I remove the --show flag, the unit test is run headerless as expected.
Hi,
This module is a good idea because renderer process is very specific. However I have a very simple but I didn't find any solution:
require
in my renderer processkarma-electron
understands my require which is a good improvement in comparison of other karma pluginsIs it normal and is there a option to change this base path (basePath
in karma doesn't change this path) ?
I hope my question is quite understandable.
Thanks
repo with bug example https://github.com/estebanabaroa/karma-electron-sqlite3-bug
describe('try sqlite3', () => {
it('try sqlite3', async () => {
console.log('before')
await new Promise(resolve => {
const db = new window.sqlite3.Database(':memory:')
db.close(resolve)
})
console.log('after') // this never gets called
})
})
window.sqlite3 = require('sqlite3').verbose()
module.exports = function (config) {
config.set({
frameworks: ['mocha'],
client: {
mocha: {timeout: 60000},
useIframe: false,
},
plugins: [require('karma-electron'), require('karma-mocha')],
basePath: './',
files: ['**/*.test.js'],
customLaunchers: {
CustomElectron: {
base: 'Electron',
browserWindowOptions: {
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload: require('path').resolve(__dirname, 'preload.js'),
},
show: false,
},
},
},
browsers: ['CustomElectron'],
singleRun: true,
autoWatch: false,
port: 9371,
colors: true,
logLevel: config.LOG_INFO,
browserNoActivityTimeout: 60000,
browserDisconnectTimeout: 60000,
browserDisconnectTolerance: 5,
})
}
Karma is deprecated and no longer accepting features and bug fixes.
I've been using @web/test-runner
and it is absolutely amazing. It is much simpler, easier, faster than Karma, without the issues (source maps just work, configs are simple)), with a much better test dev/debug experience (the interactive menu in watch mode lets you focus and open tests in a browser tab very easily with devtools automatically opened), supporting vanilla ES Module workflows with import maps (specify different import maps for different files based on globs, useful for not only mapping dependencies, but also for basic mocking).
I can't really do it justice with these words. If you haven't tried it yet, you are going to love it. It is so much better than Karma in so many ways.
It has a collection of launchers, but one it doesn't have is an electron launcher!
I'm trying to use the --show
option to open an Electron window to debug tests, but a window never appears.
My config is:
// ...
module.exports = function(config) {
config.set({
frameworks: ['jasmine', 'stacktrace'],
reporters: ['spec'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
// singleRun: false,
concurrency: Infinity,
basePath: CWD,
browsers: ['CustomElectron'],
customLaunchers: {
CustomElectron: {
base: 'Electron',
flags: [
'--show'
],
}
},
files: [
'.karma-test-build/**/*.js',
],
preprocessors: {
'.karma-test-build/**/*.js': ['electron'],
},
client: {
useIframe: false,
loadScriptsViaRequire: true,
},
})
}
Then I'm running
./node_modules/.bin/karma start --no-single-run --browsers Electron ./config/karma.config.js
I see the Electron icon in my macOS dock, but no window. If I change --no-single-run
to --single-run
, then I'll see tests successfully fly by in my terminal.
What may be missing?
hi
I have Single Page Application built with VueJS . I want to unit test my Vue Components when it is inside Electron browser . when I run the app it is hang in electron without running the tests .
this is my karma.conf.js
module.exports = function (config) {
config.set({
browsers: ['VisibleElectron'],
customLaunchers: {
VisibleElectron: {
base: 'Electron',
flags: ['--show']
}
},
frameworks: ['mocha', 'sinon-chai'],
reporters: ['spec'],
files: ['./index.js'],
preprocessors: {
'./index.js': ['webpack', 'electron', 'sourcemap'],
},
client: {
useIframe: false
},
webpack: require('./webpack.testing.js'),
webpackMiddleware: {
noInfo: true
}
})
}
this is my webpack.testing.js
let path = require('path')
let merge = require('webpack-merge')
let baseConfig = require('../../build/webpack.base.conf')
let utils = require('../../build/utils')
let webpack = require('webpack')
let projectRoot = path.resolve(__dirname, '../../')
var webpackConfig = merge(baseConfig, {
// use inline sourcemap for karma-sourcemap-loader
module: {
loaders: utils.styleLoaders()
},
devtool: '#inline-source-map',
vue: {
loaders: {
js: 'isparta'
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../../config/test.env')
})
]
})
// no need for app entry during tests
delete webpackConfig.entry
// make sure isparta loader is applied before eslint
webpackConfig.module.preLoaders = webpackConfig.module.preLoaders || []
webpackConfig.module.preLoaders.unshift({
test: /\.js$/,
loader: 'isparta',
include: path.resolve(projectRoot, 'src')
})
// only apply babel for test files when using isparta
webpackConfig.module.loaders.some(function (loader, i) {
if (loader.loader === 'babel') {
loader.include = path.resolve(projectRoot, 'test/unit')
return true
}
})
module.exports = webpackConfig
this is the output from running npm run unit
$ npm run unit
> [email protected] unit /opt/projects/desktop/testing-pro
> karma start test/unit/karma.conf.js
20 09 2016 12:23:25.962:WARN [karma]: No captured browser, open http://localhost:9876/
20 09 2016 12:23:26.005:INFO [karma]: Karma v0.13.22 server started at http://localhost:9876/
20 09 2016 12:23:26.025:INFO [launcher]: Starting browser Electron
20 09 2016 12:23:29.725:INFO [Electron 1.4.0 (Node 6.5.0)]: Connected on socket /#G-hZY5yCMogandjcAAAA with id 61156342
I use vue-cli to scaffold the app with karma support . and installed karma-electron and changed the config with it
can you help me fix this problem and run the unit tests ?
Description
After updating my application to Electron 5, I needed to use the workaround in #38 (comment) to enable the nodeIntegration.
Unfortunately, I can't get the require
field within the customLaunchers
property to work.
It always just outputs:
12 06 2019 11:20:45.649:INFO [karma-server]: Karma v4.0.1 server started at http://0.0.0.0:9876/
12 06 2019 11:20:45.650:INFO [launcher]: Launching browsers CustomElectron with concurrency unlimited
12 06 2019 11:20:45.664:INFO [launcher]: Starting browser Electron
12 06 2019 11:20:46.030:ERROR [launcher]: Cannot start Electron
12 06 2019 11:20:46.030:ERROR [launcher]: Electron stdout:
12 06 2019 11:20:46.030:ERROR [launcher]: Electron stderr:
12 06 2019 11:20:46.105:INFO [launcher]: Trying to start Electron again (1/2).
Reproduction
(1) Clone https://github.com/Jusonex/karma-electron-testapp
(2) npm install
(3) npm test
The mentioned repository contains only a default Angular installation and https://github.com/Jusonex/karma-electron-testapp/commit/66a173d8ffb3d220cd8ba4b24d0fc5f81e14ad25.
Additional Notes
require
is an absolute path and definitely correctrequire('/absolute/path/to/file')
after https://github.com/twolfson/karma-electron/blob/master/lib/electron-launcher.js#L40-L42 it worksThe require
option for karma-electron operates in the main process. But having one that require
s stuff in the renderer processes might be useful (f.e. maybe I could find a way to hack the node require paths that way, which might help with #44).
Line 58 in f40ee1e
I was trying to upgrade locally but I ran into this issue.
26 03 2021 16:02:24.565:INFO [karma-server]: Karma v6.3.1 server started at http://localhost:9876/
26 03 2021 16:02:24.566:INFO [launcher]: Launching browsers AngularElectron with concurrency unlimited
26 03 2021 16:02:24.574:INFO [launcher]: Starting browser Electron
√ Browser application bundle generation complete.
26 03 2021 16:02:44.268:INFO [Electron 12.0.2 (Node 14.16.0)]: Connected on socket rmlyL4_NcCgYp2qTAAAB with id 14501640
Electron 12.0.2 (Node 14.16.0) ERROR
An error was thrown in afterAll
Uncaught ReferenceError: require is not defined
ReferenceError: require is not defined
My release build and local builds works, it's only my unit tests that fail.
I started from a boilerplate but as I understand it, this plugin provides Karma with the ability to test with require
so hopefully this is a good place to ask.
If you have any suggestions that would be appreciated also!
I'm trying to get an angularjs-app, which I package with electron, to play together with karma-electron. Previously we used PhantomJS, but I would like to move away from this. The problem is that in a couple of places I have a require('electron').remote.require('./main.js')
to get access to some Node stuff from within the renderer process. I cannot seem to get this to work. Using the full path of main.js
makes it work, but that is (obviously) undesirable.
I have set __filenameOverride
to the location of index.html
and loadScriptsViaRequire
is set to true
. Doesn't seem to make a difference. Clearly, the require
is looking in the wrong place for my script (it's in the same directory as index.html
). What magic is required to get it working? Issue #11 seems to suggest that it should just work, but doesn't provide me with the detail to get it working in my case...
I have this config (relevant parts):
basePath: CWD,
files: [
{ pattern: 'src/**/!(*.test).js', included: false },
'src/**/*.test.js',
'tests/**/*.js',
],
browsers: ['Electron'],
preprocessors: {
'**/*.js': ['babel', 'electron'],
},
babelPreprocessor: {
options: {
presets: [
['@babel/preset-env', {
targets: {
node: 6,
},
modules: 'commonjs',
}],
],
sourceMap: 'inline',
},
filename: function (file) {
return file.originalPath.replace(/\.js$/, '.es5.js');
},
sourceFileName: function (file) {
return file.originalPath;
},
},
client: {
// otherwise "require is not defined"
useIframe: false,
loadScriptsViaRequire: true,
},
but when I run karma, I get an error on files that have import
syntax:
01 05 2018 12:27:02.144:INFO [karma]: Karma v2.0.2 server started at http://0.0.0.0:9876/
01 05 2018 12:27:02.146:INFO [launcher]: Launching browser Electron with unlimited concurrency
01 05 2018 12:27:02.154:INFO [launcher]: Starting browser Electron
01 05 2018 12:27:04.451:INFO [Electron 1.8.6 (Node 8.2.1)]: Connected on socket H4LijkAgFR1iQ9ZDAAAA with id 78010991
Electron 1.8.6 (Node 8.2.1) ERROR
{
"message": "Uncaught SyntaxError: Unexpected token import\nat /home/trusktr/Downloads/src/trusktr+infamous/src/core/Mixin.test.js:1:156\n\nundefined",
"str": "Uncaught SyntaxError: Unexpected token import\nat /home/trusktr/Downloads/src/trusktr+infamous/src/core/Mixin.test.js:1:156\n\nundefined"
}
Electron 1.8.6 (Node 8.2.1) ERROR
{
"message": "Uncaught SyntaxError: Unexpected token import\nat /home/trusktr/Downloads/src/trusktr+infamous/src/core/TreeNode.test.js:1:156\n\nundefined",
"str": "Uncaught SyntaxError: Unexpected token import\nat /home/trusktr/Downloads/src/trusktr+infamous/src/core/TreeNode.test.js:1:156\n\nundefined"
}
But, if I remove electron
from preprocessors, so that I only have babel
,
preprocessors: {
'**/*.js': ['babel'],
},
then that syntax error goes away which makes me think now Babel is working, but then I get these errors:
01 05 2018 12:34:14.485:INFO [karma]: Karma v2.0.2 server started at http://0.0.0.0:9876/
01 05 2018 12:34:14.488:INFO [launcher]: Launching browser Electron with unlimited concurrency
01 05 2018 12:34:14.527:INFO [launcher]: Starting browser Electron
01 05 2018 12:34:17.042:INFO [Electron 1.8.6 (Node 8.2.1)]: Connected on socket Tlf5sbG62C1vrybuAAAA with id 16665817
Electron 1.8.6 (Node 8.2.1) ERROR
{
"message": "Uncaught Error: Cannot find module './Mixin'\nat module.js:487:5\n\nundefined",
"str": "Uncaught Error: Cannot find module './Mixin'\nat module.js:487:5\n\nundefined"
}
Electron 1.8.6 (Node 8.2.1) ERROR
{
"message": "Uncaught Error: Cannot find module './TreeNode'\nat module.js:487:5\n\nundefined",
"str": "Uncaught Error: Cannot find module './TreeNode'\nat module.js:487:5\n\nundefined"
}
So, it seems that when I add electron
to preprocessors, babel
stops working. But when I don't have electron
, then it doesn't know how to resolve the modules.
Any ideas how to make it work with karma-babel?
I have followed this https://github.com/twolfson/karma-electron/blob/3.2.1/docs/submodules.md to config my karma.
There is no error, but I didn't get any feed back from my test or any js files.Then I modified a file and save it. It seem electron was pending. and log this:
20 06 2016 18:14:31.646:INFO [karma]: Delaying execution, these browsers are not ready: Electron 1.2.3 (Node 6.1.0)
this.electron = window ? window['electron'] : null;
this.listener$ = this.replaySubject.asObservable();
if (!this.electron) {
console.log('Developing with web browser...');
} else {
this.ipcRenderer.on(
ELECTRON_CH.BRIDGE.CLIENT,
(event, message) => {
console.log('ipcRenderer event:', event);
this.replaySubject.next(message);
});
}
When I run the application, it alway running on the web browser, not an app!
How can I config application for run like app
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.