Webstorm 10 + Karma + ES6 - Unit testing - node.js

First let me start by mentioning that all my unit tests works perfectly using gulp.
I'm trying to run my unit tests via Webstorm (v10) the problem is that the the karam.conf.js is pointing to the compiled js files, and not to the original files... is there a way to tell Webstorm to compile the files first before it runs the tests?
here is my karam.conf.js: (please note that the pre-compiled files are at the same location but looks like *.spec.js)
module.exports = function (config) {
'use strict';
config.set({
basePath: '',
frameworks: ['mocha'],
files: [
'bundledTests/test/**/*.spec.bundle.js'
],
// reporters configuration
reporters: ['mocha'],
plugins: [
'karma-mocha-reporter',
'karma-mocha',
'karma-phantomjs-launcher',
'karma-chrome-launcher'
],
//reporters: ['progress'],
port: 9876,
colors: true,
autoWatch: true,
singleRun: false,
usePolling: true,
atomic_save: false,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
browsers: ["Chrome"] //'PhantomJS',
});
};
Any help would be much appreciated!

Use karma-babel-preprocessor.
Add preprocessors section into your karma.conf.js:
preprocessors: {
'src/**/*.js': ['babel'],
'test/**/*.js': ['babel']
},
Mark paths which need to be processed before running in tests.

Related

Karma test runner error: "An error was thrown in afterAll\nTypeError: _fs2.default.readdirSync is not a function"

I have been trying to trigger the browser and open Google using Karma with Jasmine.
Karma console is giving the following error:
Karma error message
Selenium-standalone log:
Selenium standalone log
Karma.conf.js->
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
plugins: [
'karma-browserify',
'karma-jasmine',
'karma-firefox-launcher'
],
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['browserify','jasmine'],
// list of files / patterns to load in the browser
files: [
'../../../scripts/jasmineTest.spec.js'
],
// list of files / patterns to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'../../../scripts/jasmineTest.spec.js' : [ 'browserify' ]
},
browserify: {
debug: true,
// transform: [ 'brfs' ]
},
// 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: ['Firefox'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
My Jasmine script:
var wdio = require('../webdriverio')
describe("Jasmine test", function(){
var client = {}
client = wdio.remote({
desiredCapabilities: {
browserName: 'firefox'
}
})
client.init()
client.url("https://www.google.co.in")
it("test-1", function(done){
// expect(false).not.toBe(true)
// expect(2).toEqual(2)
done()
})
it("test-2", function(done){
// var a = ['A','B','C']
// expect(a).toContain('D')
done()
})
})

Karma: Executed 0 of 0 Error

I think I have everything set up properly. I followed the specs of the Karma Tutorial for RequireJS, but everything I've tried seems to result in the same error.
It appears that my test-main.js file is being loaded since a console.log() will fire. However, in the Object.keys loop, the files will get listed, but TEST_REGEXP fails so the allTestFiles ends up being an empty array. I'm sure it's something silly, but it's created just like the Tutorial - with the exception of using node_modules for jquery, require, underscore.
My test-main.js file:
var allTestFiles = [];
var TEST_REGEXP = /test\.js$/;
var pathToModule = function(path) {
return path.replace(/^\/base\//, '').replace(/\.js$/, '');
};
Object.keys(window.__karma__.files).forEach(function(file)
{
if(TEST_REGEXP.test(file))
{
// Normalize paths to RequireJS module names
allTestFiles.push(pathToModule(file));
}
});
if(console) console.log(allTestFiles);
require.config(
{
// Karma serves files under /base, which is the basePath from the config file
baseUrl: '/base/src',
paths:
{
'jquery':'../node_modules/jquery/dist/jquery',
'underscore':'../node_modules/underscore/underscore-min'
},
shim:
{
'underscore': { exports: '_' }
},
// dynamically load all test files
deps: allTestFiles,
// kick off jasmine, as it is asynchronous
callback: window.__karma__.start
});
My karma.conf.js file:
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: [
'test/test-main.js',
{pattern: 'node_modules/jquery/dist/jquery.js', included: false},
{pattern: 'src/*.js', included: false},
{pattern: 'test/**/*Spec.js', included: false}
],
// list of files to exclude
exclude: [
'src/main.js'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// 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: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
I came across a solution to the problem.
I ended up changing my test-main.js file above the require.config section to this:
// Karma RequireJS configuration
var tests = [];
for (var file in window.__karma__.files) {
if (/Spec\.js$/.test(file)) {
tests.push(file);
}
}
If I simply changed TEST_REGEXP to /Spec\.js$/ I ended up getting a timestamp error. I don't know why. More interesting is why following the guide produces errors. But it is all working now.

Requirejs do not add ".js" for modules using karma

I have simple test, that must work in webstorm using karma and requirejs.
The problem is that for some reason requirejs do not add ".js" for modules i was loading for tests. So it crashed trying to load "../ts/mamats/mama", while "../ts/mamats/mama.js" exists
Test (main.jasmine.js):
define(["require", "exports", "../ts/mamats/mama"], function(require, exports, mama) {
describe("first test", function () {
it("should be true", function () {
var object = new mama.block();
expect(object instanceof mama.block).toBe(true);
});
});
});
//# sourceMappingURL=main.jasmine.js.map
every thing works correctly when i replace "../ts/mamats/mama" with "../ts/mamats/mama.js"
sourceMappingURL here because javaScript file generated from typeScript source file, and because of that i cannot add ".js" for modules manually
Test starts with this entry point (main-test.js):
var tests = Object.keys(window.__karma__.files).filter(function (file) {
return (/\.jasmine\.js$/).test(file);
});
requirejs.config({
baseUrl: '/base',
deps: tests,
callback: window.__karma__.start
});
Why requirejs don't add ".js" for modules here?
Karma conf file:
module.exports = function(config) {
config.set({
basePath: '../',
frameworks: ['jasmine', 'requirejs'],
files: [
'static-tests/main-test.js',
{ pattern: 'static/**/*', included: false },
{ pattern: 'static-tests/**/*', included: false }
],
exclude: [],
preprocessors: {},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
singleRun: false
});
};
Here is an interesting read on how RequireJs handles this:
http://requirejs.org/docs/api.html#jsfiles
Reading that makes it seem like an issue with RequireJS, but there seems to be some debate on whether or not that is true. Regardless, this gist seems to solve the issue.
var tests = Object.keys(window.__karma__.files).filter(function (file) {
return /\.spec\.js$/.test(file);
}).map(function(file){
return file.replace(/^\/base\/src\/js\/|\.js$/g,'');
});
require.config({
baseUrl: '/base/src/js'
});
require(tests, function(){
window.__karma__.start();
});
It looks like trouble in require.js
The problem is in next:
1. When in deps appear absolute path - requirejs stop add ".js" for any require call
2. When in deps appear file with extension, for some reason requirejs again stop add ".js" for modules
Other Solution here - to replace bathUrl and add it to requirejs conf do not help.
For me solution is next:
var tests = Object.keys(window.__karma__.files).filter(function (file) {
return (/\-jasmine\.js$/).test(file);
}).map(function (file) {
return file.replace(/^\/|\.js$/g, '');
});
and
baseUrl: '',
for requirejs.conf
and i have no idea why requirejs still add "/base" for all url that are requested, but now all works fine

Karma/PhantomJS works on Windows, same config on Linux fails to send messages to PhantomJS

I had an existing build using Maven, Karma, PhantomJS, and Jasmine working in Windows7, using a Cygwin Bash shell.
I'm now trying to get the same build running on a CentOS VM pointing to the same workspace.
When I run Karma on the VM, it starts Karma and PhantomJS "because no message in 10000 ms". I tried increasing the capture timeout, but that made no difference.
Is there something I can do to get more diagnostics that might tell me why no messages are getting to PhantomJS from Karma?
On Windows, I'm using Karma v0.12.16 and PhantomJS 1.9.7. On the CentOS VM, I'm using Karma v0.12.24 and PhantomJS 1.9.8.
Here's my "karma.config.js":
module.exports = function(config) {
'use strict';
config.set({
basePath: '../../../..',
frameworks: ['jasmine'],
files: [
"http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js",
"http://code.jquery.com/jquery-migrate-1.2.1.js",
"src/main/webapp/js/libs/jquery.coo.kie.js",
"src/main/webapp/js/libs/jquery.address-1.3.1.js",
"src/main/webapp/js/libs/modernizr-1.6.min.js",
"src/main/webapp/js/libs/underscore.js",
"src/main/webapp/js/mylibs/util.js",
"src/main/webapp/js/mylibs/controller.js",
"src/test/webapp/js/init.js",
"src/main/webapp/js/mylibs/config.js",
"src/main/webapp/js/mylibs/controller.daily.js",
"src/main/webapp/js/mylibs/controller.daily.rate-table.js",
"src/main/webapp/js/mylibs/controller.diagnostic.page.js",
"src/main/webapp/js/mylibs/controller.realtime.matrix-view.js",
"src/main/webapp/js/mylibs/controller.realtime.rate-table.js",
"src/main/webapp/js/mylibs/controller.realtime.subway-map.js",
"src/main/webapp/js/mylibs/data.daily.js",
"src/main/webapp/js/mylibs/data.realtime.js",
"src/main/webapp/js/mylibs/diagnostic.controller.js",
"src/main/webapp/js/mylibs/html.js",
"src/main/webapp/js/mylibs/html.daily.js",
"src/main/webapp/js/mylibs/html.diagnostic.js",
"src/main/webapp/js/mylibs/html.realtime.js",
"src/main/webapp/js/mylibs/html.realtime.matrix-view.js",
"src/main/webapp/js/mylibs/routes.js",
"src/main/webapp/js/mylibs/uverse.config.js",
"src/test/webapp/js/data.daily.test.js",
"http://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js",
"http://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular-resource.js",
"src/test/webapp/js/libs/angular-mocks.js",
"src/main/webapp/js/diag/libs/ui-bootstrap-tpls-0.10.0.js",
"src/main/webapp/js/diag/libs/ng-table.src.js",
"src/main/webapp/js/diag/constants.js",
"src/main/webapp/js/diag/diagapp.js",
"src/main/webapp/js/diag/diagMod.js",
"src/main/webapp/js/diag/dataSourcesMod.js",
"src/main/webapp/js/diag/queriesMod.js",
"src/main/webapp/js/diag/handlersMod.js",
"src/main/webapp/js/diag/workflowMappingsMod.js",
"src/main/webapp/js/diag/configurationMod.js",
"src/main/webapp/js/diag/commonErrorsMod.js",
"src/test/webapp/js/diag/diagapp.test.js"
],
exclude: [
],
plugins:[
'karma-jasmine',
'karma-coverage',
'karma-junit-reporter',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-ie-launcher'
],
preprocessors: {
"src/main/webapp/js/mylibs/*.js": 'coverage',
"src/main/webapp/js/diag/*.js": 'coverage',
},
coverageReporter: {
type: "lcov",
dir: "target/karma-coverage"
},
junitReporter: {
outputFile: 'target/surefire-reports/TEST-karma.xml'
},
reporters: ['dots', 'junit'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
captureTimeout: 60000,
singleRun: false
});
};
And here is the Karma command line I'm running:
karma start /media/sf_Users/<myuid>/workspace2/SunlightGUI/src/test/webapp
/js/karma.conf.js --browsers PhantomJS --reporters dots,junit,coverage
--single-run --no-auto-watch --colors false --log-level info
Use the following process:
Open karma.conf.js
Remove websocket from transports:
transports: ['flashsocket', 'xhr-polling', 'jsonp-polling']
Use polling:
usePolling: true
Use require("os").cwd() to get the absolute path
Use a variable to store the absolute path with a slash, such as:
var foo = process.cwd() + "/";
config.set({
basePath: foo,
Prefix each path in the files array with the absolute path, for example:
foo + 'src/test/webapp/js/diag/diagapp.test.js',
References
Karma Changelog
Karm Commit: Make transports configurable

karma cannot load files injected by requirejs

I'm having troubles getting a simple karma test to run. I have the following code structure:
js/
|-- tests.js
|-- karma.config.js
|-- app/
|-- controllers.js
|-- tests/
|-- unit/
|-- loginSpec.js
|-- vendor/
|-- jquery.js
I'm following the documentation at http://karma-runner.github.io/0.8/plus/RequireJS.html and have my configuration set up as follow (minus the unimportant parts):
// base path, that will be used to resolve files and exclude
basePath = '';
// list of files / patterns to load in the browser
files = [
JASMINE,
JASMINE_ADAPTER,
REQUIRE,
REQUIRE_ADAPTER,
'tests.js',
{pattern: 'tests/unit/*.js', included: false}
];
In my controllers.js, I define a function called LoginCtrl and I want to test this function in loginSpec.js
define(['controllers'],function(controllers) {
describe('Login controllers', function() {
describe('LoginCtrl', function(){
it('should return 1', function() {
var scope = {},
ctrl = new LoginCtrl(scope);
expect(1).toBe(1);
});
});
});
});
The problem is my browser cannot load the controllers.js file eventhough I've set up my main test file's requirejs configuration (tests.js) as follow:
var tests = Object.keys(window.__karma__.files).filter(function (file) {
return /Spec\.js$/.test(file);
});
requirejs.config({
baseUrl: '/base/app',
paths: {
jquery: 'vendor/jquery',
},
deps: tests,
callback: window.__karma__.start
});
The browser does look for a file at http://localhost:9876/base/app/controllers.js. Isn't this the right path?
The path is not okay I think, it should be jquery: '../vendor/jquery', because the requirejs base points to the app dir. But this is not the only problem...
By karma you should add every file to the patterns you want to use. The files with the flag include: true will be runned by karma, the others can be used by tests. If two patterns cover a file name then the first pattern will override the second (so this is in reverse order than we usually do). In your case you should use something like this as karma.conf.js:
module.exports = function (config) {
config.set({
basePath: './',
frameworks: ['jasmine', 'requirejs'],
files: [
{pattern: 'tests.js', included: true},
{pattern: 'test/**/*.js', included: false},
{pattern: 'app/**/*.js', included: false},
{pattern: 'vendor/**/*.js', included: false}
],
exclude: [
],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Firefox'],
captureTimeout: 6000,
singleRun: false
});
};
I had the similar problem, but I didn't find nice solution. I had to apply "hack" by adding .js extension to in my spec file, in your case try to change 'controllers' to 'controllers.js' in your loginSpec.js

Resources