I am trying to write unit tests for my reactjs code using Jasmine with the Karma test runner - automated with gulp. I am having an issue where my test spec includes import statements which are then not being picked up by the test body.
Here is my test spec:
import React from 'react';
import Utils from 'react-dom/test-utils';
import {MyClass} from "../Path/MyCodeFile.jsx";
describe('MyClass', function () {
it('can render without error', function () {
var component;
var element = React.createElement(
MyClass,
{}
);
expect(function () {
component = Utils.renderIntoDocument(element);
}).not.toThrow();
});
})
My Karma config file:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'spec/*[Ss]pec.js',
'wwwroot/js/site.js'
],
exclude: [
],
preprocessors: {
'spec/*[Ss]pec.js': ['babel']
},
babelPreprocessor: {
options: {
presets: ['es2015', 'env'],
plugins: ["transform-es2015-modules-umd"]
}
},
reporters: ['progress', 'junit'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
plugins: [
'karma-jasmine',
'karma-junit-reporter',
'karma-chrome-launcher',
'karma-babel-preprocessor'
],
singleRun: true,
concurrency: Infinity
});
}
My gulp task:
var gulp = require('gulp');
var Server = require('karma').Server;
gulp.task('unittest', function (done) {
new Server({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, function () {
done();
}).start();
});
And this is the message I get when running the task:
[21:17:11] Starting 'unittest'...
02 08 2018 21:17:13.030:INFO [karma]: Karma v2.0.5 server started at http://0.0.0.0:9876/
02 08 2018 21:17:13.030:INFO [launcher]: Launching browser Chrome with unlimited concurrency
02 08 2018 21:17:13.046:INFO [launcher]: Starting browser Chrome
02 08 2018 21:17:14.969:INFO [Chrome 67.0.3396 (Windows 10 0.0.0)]: Connected on socket peUBczU20NB36DSvAAAA with id 73989234
Chrome 67.0.3396 (Windows 10 0.0.0): Executed 0 of 1 SUCCESS (0 secs / 0 secs)
Chrome 67.0.3396 (Windows 10 0.0.0) MyClass can render without error FAILED
TypeError: Cannot read property 'createElement' of undefined
at <Jasmine>
at UserContext.<anonymous> (spec/applicationSpec.js:31:43)
at <Jasmine>
Chrome 67.0.3396 (Windows 10 0.0.0): Executed 1 of 1 (1 FAILED) (0 secs / 0.003 secs)
Chrome 67.0.3396 (Windows 10 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.02 secs / 0.003 secs)
[21:17:15] Finished 'unittest' after 3.6 s
It's as if the import statement isn't there.
After some pain, I have found an alternative approach which successfully runs the tests. My new test spec:
describe('MyClass', function () {
var React;
var Utils;
var MyClasses;
beforeAll(() => {
React = require("react");
Utils = require("react-dom/test-utils");
MyClasses = require("../Path/MyClass.jsx");
});
it('can render without error', function () {
var component;
var element = React.createElement(
MyClasses.MyClass,
{}
);
expect(function () {
component = Utils.renderIntoDocument(element);
}).not.toThrow();
});
})
and my updated Karma config:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', 'browserify'],
files: [
'spec/*[Ss]pec.js',
'wwwroot/js/site.js'
],
exclude: [
],
preprocessors: {
'spec/*[Ss]pec.js': ['browserify']
},
browserify: {
debug: true,
transform: [
['babelify', {
presets: [
"#babel/preset-env",
"#babel/preset-react"
]
}]
],
extensions: ['.jsx']
},
reporters: ['progress', 'junit'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
plugins: [
'karma-jasmine',
'karma-junit-reporter',
'karma-chrome-launcher',
'karma-babel-preprocessor',
'karma-browserify'
],
singleRun: true,
concurrency: Infinity
});
}
Related
I have a bunch of tests that are totaly ignored.
I also looked for everywhere in the project for fdescribe, fit, xdescribe, xit, ddescribe or iit but there are none remainning. I just have a few xit but not much.
It seems to ignore all tests in a my /modules/ folder but it doesn't seem to be caused by misconfiguration because if I use fdescribe on some of them those are executed properly. Here is my karma.conf.js anyway in case you are intrested :
'use strict';
const stringify = require('stringify');
const babelify = require('babelify');
module.exports = (config) => {
config.set({
basePath: '',
frameworks: ['browserify', 'jasmine'],
files: [
'node_modules/jquery/dist/jquery.min.js',
'node_modules/angular/angular.js',
'node_modules/angular-route/angular-route.min.js',
'node_modules/angular-permission/dist/angular-permission.js',
'node_modules/angular-permission/dist/angular-permission-ng.js',
'node_modules/angular-sanitize/angular-sanitize.min.js',
'node_modules/angular-messages/angular-messages.min.js',
'node_modules/angular-mocks/angular-mocks.js',
'src/apps/publiques/app-publiques.module.js',
'src/apps/publiques/bootstrap-test.js',
'src/**/*.spec.js'
],
// the only folder that is excluded is correctly excluded
exclude: [
'src/modules/data-table/**/*.spec.js'
],
preprocessors: {
'src/apps/publiques/app-publiques.module.js': 'browserify',
'src/apps/publiques/bootstrap-test.js': 'browserify',
'src/**/*.spec.js': 'browserify',
},
browsers: ['PhantomJS'],
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-browserify',
'karma-coverage',
'karma-mocha-reporter',
'karma-narrow-reporter',
'karma-jasmine-diff-reporter',
'karma-spec-reporter',
],
browserify: {
debug: true,
transform: [
babelify,
stringify,
],
},
reporters: [
'jasmine-diff',
// 'progress',
// 'mocha',
'narrow',
// 'spec'
],
specReporter: {
maxLogLines: 5, // limit number of lines logged per test
suppressErrorSummary: false, // do not print error summary
suppressFailed: false, // do not print information about failed tests
suppressPassed: false, // do not print information about passed tests
suppressSkipped: true, // do not print information about skipped tests
showSpecTiming: true, // print the time elapsed for each spec
failFast: true // test would finish with error when a first fail occurs.
},
mochaReporter: {
colors: {
success: 'green',
info: 'blue',
warning: 'yellow',
error: 'bgRed',
},
symbols: {
success: '+',
info: '#',
warning: '!',
error: 'x',
},
output: 'full',
},
phantomjsLauncher: {
exitOnResourceError: true,
},
port: 9876,
logLevel: config.LOG_DEBUG,
singleRun: true,
colors: true,
autoWatch: false,
});
};
End of karma log is
PhantomJS 2.1.1 (Windows 7 0.0.0) LOG: 'WARNING: Tried to load angular more than once.'
PhantomJS 2.1.1 (Windows 7 0.0.0): Executed 177 of 637 (skipped 10) SUCCESS
(0.858 secs / 0.82 secs)
[17:51:39] Karma Run Complete: No Failures
It turned out I had to beforeEach nested somewher like follow
describe('publiques-demandes-modifier.controller', () => {
beforeEach(() => {
angular.mock.module(app);
// mock window pour le test submitRedirect
const windowObj = { location: { href: '' } };
beforeEach(angular.mock.module(($provide) => {
$provide.value('$window', windowObj);
}));
angular.mock.inject((
I found out by using mocha reporter and by skipping last executed tests one by one to find the one responsible.
In an AngularJS 1 project we use Gulp to compile the project with webpack and test it with Karma. We cannot get sourcemaps to work as expected.
I found the obvious plug-in (https://www.npmjs.com/package/karma-sourcemap-loader) but this seems to exist only to use sourcemaps while debugging karma tests, NOT to display a usable stacktrace.
I also found https://www.npmjs.com/package/karma-source-map-support which seems to be exclusive for browserify.
Am I missing something here? Has anyone gotten this to work?
Appended info:
This is the unusable output (note index.module.js, the webpack compiled file, which has inline sourcemaps):
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 629 of 629 (1 FAILED) (6.663 secs / 6.531 secs)
TOTAL: 1 FAILED, 628 SUCCESS
1) should A B not be A B
TrajectDetails Controller _aMethod()
Expected Object({ a: Object({ x: [ 'A', 'B' ] }) }) not to be Object({ materieel: Object({ x: [ 'A', 'B' ] }) }).
.tmp/serve/app/index.module.js:93820:42
[11:02:26] 'test' errored after 9.37 s
[11:02:26] Error: Failed 1 tests.
This is how my karma config looks:
var preprocessors = {};
pathSrcJs.forEach(function (path) {
preprocessors[path] = ['babel', 'sourcemap'];
});
pathSrcHtml.forEach(function (path) {
preprocessors[path] = ['ng-html2js'];
});
var configuration = {
files: listFiles(),
preprocessors: preprocessors,
singleRun: true,
colors: true,
autoWatch: false,
ngHtml2JsPreprocessor: {
stripPrefix: conf.paths.src + '/',
moduleName: 'xx-xx'
},
logLevel: 'INFO',
frameworks: ['source-map-support', 'jasmine'],
browsers: ['PhantomJS'],
plugins: [
'karma-phantomjs-launcher',
'karma-coverage',
'karma-jasmine',
'karma-ng-html2js-preprocessor',
'karma-spec-reporter',
'karma-babel-preprocessor',
'karma-sourcemap-loader',
'karma-source-map-support'
],
reporters: ['progress', 'spec'],
};
config.set(configuration);
Webpack config is like this:
var webpackOptions = {
watch: watch,
module: {
loaders: [{test: /\.js$/, exclude: /node_modules/, loaders: ['ng-annotate', 'babel-loader']}]
},
output: {filename: output},
devtool = 'inline-source-map'
};
var sources = [path.join(conf.paths.src, source)];
sources.push(path.join(conf.paths.src, '/app/**/*.spec.js'));
return gulp.src(sources)
.pipe(webpack(webpackOptions))
.pipe(gulp.dest(path.join(conf.paths.tmp, '/serve/app')));
I have an Angular app with a Django back end. I am just starting with Karma and Jasmine unit testing. I am unable to inject my factory into my test suite. Is there any suggestions or glaring errors that I am making?
Here are my files...
karma.conf.js file
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'./node_modules/angular/angular.js',
'./node_modules/angular-ui-router/release/angular-ui-router.js',
'./node_modules/angular-mocks/angular-mocks.js',
'./fake/path/fake/js/directory/src/modules.js',
'./fake/path/fake/js/directory/src/factories/projectinfostorage.js',
'./fake/path/fake/js/directory/src/factories/projectinfostorage.spec.js',
],
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
Angular module...
var app = angular.module("tablebrowser", ["ngRoute"]);
Factory...
app.factory('projectInfoStorage', function(){
var factory = {};
return factory;
})
Factory Unit Test...
describe('projectInfoStorage factory', function() {
var projectInfoStorage;
beforeEach(angular.mock.module('tablebrowser'));
beforeEach(inject(function(_projectInfoStorage_) {
projectInfoStorage = _projectInfoStorage_;
}));
console.log(projectInfoStorage)
});
Karma shows me this in the command line...
Chrome 55.0.2883 (Mac OS X 10.10.5) LOG: undefined
Chrome 55.0.2883 (Mac OS X 10.10.5): Executed 0 of 0 SUCCEChrome 55.0.2883 (Mac OS X 10.10.5): Executed 0 of 0 ERROR (0 secs / 0 secs)
The reason your test doesn't work is because you haven't actually tested anything. Within that describe function you need to actually put the test in an it function. Something like below:
describe('projectInfoStorage factory', function() {
var projectInfoStorage;
beforeEach(angular.mock.module('tablebrowser'));
beforeEach(inject(function(_projectInfoStorage_) {
projectInfoStorage = _projectInfoStorage_;
}));
it('will test factory', function() {
expect(true).toBeTruthy();
}
});
You need to build your tests with these in order to test something.
I am getting following error while testing angular app.
Can't find variable: angular in spec/abc.spec.js
My app is running fine with webpack. Also karma gives success on
expect(true).toBe(true);
Following is my skeleton:
abc.ts
var angular = require('angular');
var angular_mocks = require('angular-mocks');
var specs = require('../spec/abc.spec.js');
var myApp = angular.module('myApp',[]);
myApp.controller('MyController', function($scope) {
$scope.spices = [{"name":"pasilla", "spiciness":"mild"},
{"name":"jalapeno", "spiciness":"hot hot hot!"},
{"name":"habanero", "spiciness":"LAVA HOT!!"}];
$scope.spice = "habanero";
});
abc.spec.js
describe('myController function', function () {
describe('myController', function () {
var $scope;
beforeEach(angular.mock.module('myApp'));
beforeEach(inject(function ($rootScope, $controller) {
$scope = $rootScope.$new();
$controller('MyController', {$scope: $scope});
}));
it('should create "spices" model with 3 spices', function () {
expect($scope.spices.length).toBe(3);
});
it('should set the default value of spice', function () {
expect($scope.spice).toBe('habanero');
});
it('should set the default value of spice', function () {
expect(angular).toBeDefined();
});
});
});
karma.config.js
// Karma configuration
// Generated on Wed Dec 21 2016 19:28:26 GMT+0530 (India Standard Time)
var webConfig = require('./karma.conf')
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'],
// list of files / patterns to load in the browser
files: [
'spec/*.js'
],
// list of files to exclude
exclude: [
'src/bundle.js'
],
webpack: webConfig,
webpackMiddleware: {
stats: 'errors-only'
},
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'src/*.js': ['coverage', 'webpack']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress','coverage'],
coverageReporter: {
type : 'html',
dir : '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: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// 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
})
}
webpack.config.js
var webConfig = {
entry: './src/abc',
output:{
path: 'src',
filename:'bundle.js'
},
resolve: {
root: ['src', "node_modules"],
extensions: ['', '.ts', '.js']
},
modules: {
loaders: [
{
test:/\.ts?$/,
loader:'ts-loader'
}
]
}
}
module.exports = webConfig;
tsconfig.js
{
"compilerOptions": {
"target": "es5",
"module": "amd",
"moduleResolution": "node",
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true
},
"exclude": [
"typings",
"node_modules"
]
}
ERROR:
C:\Users\namankheterpal\IdeaProjects\ngwk>karma start
webpack: bundle is now VALID.
22 12 2016 13:55:36.125:WARN [karma]: No captured browser, open http://localhost:9876/
22 12 2016 13:55:36.137:INFO [karma]: Karma v1.3.0 server started at http://localhost:9876/
22 12 2016 13:55:36.138:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
22 12 2016 13:55:36.151:INFO [launcher]: Starting browser PhantomJS
22 12 2016 13:55:37.906:INFO [PhantomJS 2.1.1 (Windows 8 0.0.0)]: Connected on socket /#GxGMuAyLHkfyOc9NAAAA with id 40162084
PhantomJS 2.1.1 (Windows 8 0.0.0) myController function myController encountered a declaration exception FAILED
ReferenceError: Can't find variable: angular in spec/abc.spec.js (line 6)
spec/abc.spec.js:6:23
spec/abc.spec.js:3:11
global code#spec/abc.spec.js:1:9
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.006 secs / 0.001 secs)
Reffrence https://github.com/webpack/karma-webpack
Please let me know if I am missing something and if any other info is required.
Thanks in advance.
Include your angular library and your source files at
files: [
'location/angular.min.js'
'spec/*.js'
],
you have to add angular library to execute karma testing and also your source files.
I have been trying to setup the Karma config for a new angular project that uses the Angular Deferred Bootstrap to load a config file (JSON). When Karma loads it gives me errors that it cannot find the app.json file.
Here is my angular module.
angular.module('CareerPortal', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize']);
// Defer the application until we have the configuration for the app!
deferredBootstrapper.bootstrap({
element: document.body,
module: 'MyApp',
resolve: {
configuration: ['$http', function ($http) {
return $http.get('app.json');
}]
}
});
Here is my karma config
function listFiles() {
var wiredepOptions = _.extend({}, conf.wiredep, {
dependencies: true,
devDependencies: true
});
return wiredep(wiredepOptions).js
.concat([
path.join(conf.paths.tmp, '/serve/app/index.module.js'),
path.join(conf.paths.src, '/**/*.spec.js'),
path.join(conf.paths.src, '/**/*.mock.js'),
path.join(conf.paths.src, '/**/*.html')
]);
}
module.exports = function (config) {
var configuration = {
files: listFiles(),
singleRun: true,
autoWatch: false,
debug: true,
frameworks: ['jasmine'],
ngHtml2JsPreprocessor: {
stripPrefix: 'src/',
moduleName: 'CareerPortal'
},
browsers: ['PhantomJS'],
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-ng-html2js-preprocessor'
],
preprocessors: {
'src/**/*.html': ['ng-html2js']
}
};
config.set(configuration);
};
And then the JSON file is just a standard JSON file.
Here is the error that I get
INFO [karma]: Karma v0.12.37 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.8 (Mac OS X 0.0.0)]: Connected on socket 6MHhNTNq1d3djLp7R0z3 with id 21194787
WARN [web-server]: 404: /app.json
PhantomJS 1.9.8 (Mac OS X 0.0.0): Executed 0 of 0 ERROR (0.001 secs / 0 secs)
[18:23:44] Finished 'test' after 1.71 s