Karma fails when using PhantomJS but not Chrome - javascript

I have a series of tests that are pass when I use the Karma Chrome Launcher but fail when I use the Karma PhantomJS launcher.
Here is my what's inside my karma.config.js file
```
frameworks: ['browserify','mocha','chai', 'sinon'],
files: require('./include.conf.js').concat([
'test/helper/*.js',
'test/example/*.spec.js',
'test/unit/*.spec.js',
'test/integration/*.spec.js'
]),
// list of files to exclude
exclude: [
'gulpfile.js',
'index.js',
'karma.conf.js'
],
browserify: {
debug: true,
transform: ['reactify'],
bundleDelay: 1000
},
preprocessors: {
'test/helper/*.js': ['browserify'],
'test/example/*.spec.js': ['browserify'],
'test/unit/*.spec.js': ['browserify'],
'test/integration/*.spec.js': ['browserify'],
'dev/js/**/*.js': ['browserify']
},
// web server port
port: 9876,
autoWatch: true,
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
plugins: [
'karma-coverage',
'karma-mocha',
'karma-browserify',
'karma-chai',
'karma-sinon',
'karma-phantomjs-launcher'
]```
All of the files are being preprocessed and running properly with the Karma Chrome Launcher, but when I try to run them with PhantomJS, I get a bunch of errors like this :
PhantomJS 1.9.8 (Mac OS X 0.0.0) ERROR
ReferenceError: Can't find variable: require
at /Users/edwinlin/Documents/repos/Picarus/dev/js/utils/database-utils.js:1
Thanks for anyone's help!

Related

Karma Tesing on Virtual Machine

I am trying to run karma tests as part of an automated TFS build. The build opens a browser window and fails to run headless on the build server. What is the best browser configuration for this scenario?
Thanks!
the package.json script is
"headlessTest":"karma start --browsers ChromeHeadless karma.conf.js"
// Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '#angular/cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('#angular/cli/plugins/karma'),
require('karma-phantomjs-launcher')
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
output in console window in TFS build
[33m01 08 2017 10:03:00.043:WARN [launcher]: [39mChromeHeadless have not captured in 60000 ms, killing.
[33m01 08 2017 10:03:02.087:WARN [launcher]: [39mChromeHeadless was not killed in 2000 ms, sending SIGKILL.
[33m01 08 2017 10:03:04.208:WARN [launcher]: [39mChromeHeadless was not``killed by SIGKILL in 2000 ms, continuing.
You can try lunching the chrome with "nosandbox".
Use following configuration in your karma project.conf.js:
browsers: ['ChromeNoSandbox'],
customLaunchers: {
ChromeNoSandbox: {
base: 'Chrome',
flags: ['--no-sandbox']
}
}
Reference this Github issue: https://github.com/karma-runner/karma-chrome-launcher/issues/73#issuecomment-236597429
UPDATE:
There is an issue for Karma : github.com/karma-runner/karma/issues/2652 , whatever you can try different versions combination for Karma and Chrome, someone mentioned that downgrading to karma 1.5 worked.
You can also try to increase the Timeout value, eg 600000, then try it again.

Webpack Karma using react/addons

I have a large-ish Angular app written in Typescript generating JS files 1:1 plus external modules such as moment and React loaded off the same server. Dependencies are handled by RequireJS.
We added some basic Angular Karma tests which worked fine. This uses a duplicate RequireJS config tweaked to load the tests into Karma.
Now I am trying to test some React components and in the process move to Webpack. So, I have modified the Karma config to use Webpack and installed the external dependencies using npm. I have spent all day trying to get this to work but I cannot find a solution which works for my setup.
karma.conf.js
var path = require('path');
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'requirejs'],
// list of files / patterns to load in the browser
files: [
'ng/*.js',
'ng/**/*.js',
'ng/**/tests/*.spec.js'
],
// list of files to exclude
exclude: [
'app.js', // Old requirejs config
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'*.js': ['webpack', 'sourcemap'],
'ng/**/*.js': ['webpack', 'sourcemap'],
'partials/**/*.html': ['ng-html2js']
},
webpack: { //kind of a copy of your webpack config
devtool: 'inline-source-map', //just do inline source maps instead of the default
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
exclude: path.resolve(__dirname, 'node_modules'),
query: {
presets: ['airbnb']
}
},
{
test: /\.json$/,
loader: 'json',
},
{
test: /\.ts$/,
loader: 'typescript',
},
],
},
externals: {
'react': true,
'react/addons': true,
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true
}
},
webpackServer: {
noInfo: true //please don't spam the console when running in karma!
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS',
'Chrome'
],
plugins: [
'karma-webpack',
'karma-sourcemap-loader',
'karma-requirejs',
'karma-ng-html2js-preprocessor',
//'karma-firefox-launcher',
'karma-chrome-launcher',
'karma-phantomjs-launcher',
'karma-jasmine'
],
babelPreprocessor: {
options: {
presets: ['airbnb']
}
},
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultanous
concurrency: Infinity,
});
};
This is what I am getting:
PhantomJS 2.1.1 (Linux 0.0.0) ERROR
ReferenceError: Can't find variable: react
at /vagrant/app/media/website/js/ng/chartApp.js:48060 <- webpack:/external "react/addons":1:0
How should I be setting this up?
This might be happening if you're using Enzyme, which uses some lazy require() calls to maintain compatibility with React 0.13 and 0.14, so Webpack isn't bundling them.
If that's the case, put this in your karma.config.js:
webpack: {
// ...whatever else you have...
externals: {
'cheerio': 'window',
'react/addons': true,
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true
}
}
If you're not using Enzyme, this might still be a solution (at least the react/addons part).
See this Karma page for details.
Here's your first problem:
"I have a large-ish Angular app written in Typescript generating JS files 1:1 plus external modules such as moment and React loaded off the same server. Dependencies are handled by RequireJS."

Karma / PhantomJS browser is started but no test result is displayed in the console

As described in the title, Karma starts PhantomJS browser but NO test result is displayed.
That's all what i get when i run karma start karma.config.js
Works fine when i use Chrome or any other browser.
EDIT:
my karma.config.js file :
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'../../../node_modules/angular/angular.min.js',
'../../../node_modules/angular-mocks/angular-mocks.js',
'../app/**/*.js',
'unitTest/*.js'
],
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['PhantomJS'],
singleRun: false,
concurrency: Infinity
})
}
EDIT 2:
Problem solved. All i needed was to turn on karma watcher (autoWatch: true).
To help others: the answer is in the question:
All i needed was to turn on karma watcher (autoWatch: true).

Karma Coverage and Babel+Browserify Preprocessing

I'm using Karma to test my ES6 code. When I add karma-coverage to the mix, I need to add all the source files for the coverage tool to make a useful report, but when I do that, Karma gives me this error in all browsers:
PhantomJS 1.9.8 (Mac OS X 0.0.0) ERROR
Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.
at /var/folders/55/9_128mq95kz1q_2_vwy7qllw0000gn/T/41cf272955d73fbba8ad1df941172139.browserify:46444:0 <- ../../node_modules/react/lib/invariant.js:49:0
My Karma config file is:
basePath: '',
browserNoActivityTimeout: 100000,
frameworks: ['phantomjs-shim', 'mocha', 'chai', 'browserify'],
files: [
'./client/**/*.js',
'./client/**/*.spec.js'
],
exclude: [
'./client/dist/*.js',
],
preprocessors: {
'./client/**/*.js': ['browserify', 'sourcemap', 'coverage']
},
browserify: {
debug: true,
transform: [
['babelify', {
optional: ["runtime"],
plugins: ["rewire"]
}],
]
},
coverageReporter: {
instrumenters: { isparta : require('isparta') },
instrumenter: {
'**/*.js': 'isparta'
},
type : 'html',
dir : './coverage/'
},
reporters: ['mocha', 'coverage'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome', 'Firefox', 'Safari', 'PhantomJS'],
singleRun: true
If I remove './client/**/*.js', from the files array, the tests work, but then the coverage only show me the tests code. I use Karma from gulp with gulp-karma, but I suppose that this doesn't have anything to do with the problem.
I had that same problem, which in my case occurred because React couldn't find the element in which it needed to render the html.
I found a quick fix by adding the following if statement into my main js file:
if ($('#container').length <= 0) {
$('body').prepend('<div id="container"></div>');
}
ReactDom.render(
<App />,
document.getElementById('container')
);
I'm aware this must not be the best way of fixing it, but at least it works for now. If anyone knows of a better way, please let us know!
Code you are covering is trying to render component into DOM node. Your code relys that it already exists (somewhere in index.html or whatever). But PhantomJS cannot find that DOM node.
You should create it before calling ReactDOM.render or search how to change template of html page used by phantom to run tests (there are plugins doung this).

Grunt Karma runs tests but blocks

I have a grunt task to run Karma unit tests using Phantom JS. The tests run but the task doesn't exit. This blocks any other task from starting till I manually kill the karma:unit task using ctrl+c.
My karma.conf.js file is:
// Karma configuration
// Generated on Thu Mar 06 2014 13:17:21 GMT-0500 (Eastern Standard Time)
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// frameworks to use
frameworks: ['mocha', 'requirejs', 'chai', 'sinon'],
// list of files / patterns to load in the browser
files: [
{ pattern: 'src/vendor/**/*.js', included: false },
{ pattern: 'src/*.js', included: false },
{ pattern: 'src/app/*_test.js', included: false },
{ pattern: 'src/app/**/*.js', included: false },
{ pattern: 'src/app/*_test.js', included: false },
'test-main.js'
],
// list of files to exclude
exclude: [
'src/app/main.js',
'**/Gruntfile.js'
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['progress', 'coverage'],
preprocessors: {
'src/app/**/!(*_test).js': 'coverage'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 10000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: true
});
};
My Grunt config for the karma task is:
karma: {
options: {
configFile: 'karma.conf.js'
},
unit: {
autowatch: true,
singleRun: true,
}
},
When I run grunt karma:unit, I get:
Running "karma:unit" (karma) task
INFO [karma]: Karma v0.12.0 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.7 (Windows 7)]: Connected on socket V2NFfUtyUi_gl0gWqbov with id 17494532
PhantomJS 1.9.7 (Windows 7): Executed 2 of 2 SUCCESS (0.012 secs / 0 secs)
but it never gets to Done, without errors until I press ctrl+C
I reinstalled karma and PhantomJS in the project and the problem cleared. I noticed that when I changed my karma configuration to use Chrome, everything worked normally so I figured the issue had to be with PhantomJS
npm install karma --save-dev
npm install phantomjs --save-dev

Categories

Resources