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.
Related
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 am configuring my Karma amd mocha framework with grunt in my project.
When I am running karma start I am getting below mentioned error.
Uncaught Error: [$injector:modulerr] Failed to instantiate module myModule due to: Error: [$injector:nomod] Module 'myModule' is not available!
My controller:
(function () {
var module = angular.module('myModule',[]);
module.controller('myCtrl', function($scope, $q, $rootScope, templateValuesSrv) {
function() {
var self = this;
self.firstName = '';
self.lastName = '';
self.getFullName = function() {
return self.firstName + ' ' + self.lastName;
};
return self;
}
});
})();
My Controller Spec:
describe('myCtrl', function() {
beforeEach(module('myModule'));
describe('getFullName()', function() {
it('should handle names correctly', inject(function($controller) {
var myController = $controller('myCtrl');
myController.firstName = 'George';
myController.lastName = 'Harrison';
myController.getFullName().should.equal('George Harrison');
}));
});
});
My Karma.conf.js
// Karma configuration
// Generated on Fri Nov 27 2015 11:48:47 GMT+0530 (India Standard Time)
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: ['mocha', 'chai'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'test/specs/*.js',
//'test/*.js'
],
// list of files to exclude
exclude: [
],
// 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: ['PhantomJS', 'Chrome'],
// 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
})
}
Please suggest what I am missing.
Before the specs you should add the js files that you want to test.
// Karma conf
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'src/**/*.js',
'test/specs/*.js',
//'test/*.js'
],
If you use a bundler like webpackt or bower then you could require then on each spec
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: [
'../scripts/bower_components/angularjs/angular.js',
'../scripts/bower_components/angular-mocks/angular-mocks.js',
'../scripts/app.js',
'../scripts/11.js',
'../scripts/controllers/*.js',
'../scripts/directives/*.js',
'../scripts/services/*.js',
'controllers/controllersTests.js',
],
// list of files to exclude
exclude: [
],
// 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: ['PhantomJS', 'PhantomJS_custom'],
customLaunchers: {
'PhantomJS_custom': {
base: 'PhantomJS',
options: {
windowName: 'my-window',
settings: {
webSecurityEnabled: false
},
},
flags: ['--load-images=true'],
debug: false
}
},
phantomjsLauncher: {
// Have phantomjs exit if a ResourceError is encountered (useful if karma exits without killing phantom)
exitOnResourceError: true
},
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
I need to test code of controllers, but i can't see right result, code below:
"slide" array length = 4; but in test i write "toBe(2)" and i see:
PhantomJS 1.9.8 (Linux 0.0.0): Executed 0 of 0 ERROR (0.035 secs / 0 secs)
Why i see 0 errors, if I expect 2, but array length is 4 ???
app.controller('mainCtrl',['$scope', function($scope){
$scope.slide = [1, 2, 3, 4];
}]);
describe('Tests Controllers', function() {
beforeEach(module('app'));
var $controller;
beforeEach(inject(function(_$controller_, $rootScope){
$controller = _$controller_;
it('check slides length, it should be 4', function() {
var $scope = {};
var controller = $controller('mainCtrl', { $scope: $scope });
expect($scope.slide.length).toBe(2);
});
}));
});
When Karma can't find your tests and displays Executed 0 of 0 ERROR, the most popular reasons which lead to this behavior are:
bad path to a test file/folder in karma.conf.js in the files:[] option
missing specs (it blocks) in the test file/folder, so Karma has nothing to execute. It may occur also if specs are placed inappropriately within a test file, like in your case you've put it inside beforeEach, but Jasmine does not support it. The idea is to put them on the same level. it spec can live separately in the global scope or right within describe suite blocks.
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
I have been learning AngularJS and the time has come to start writing tests but I'm falling at the first hurdle.
My karma config file is:
module.exports = function(config) {
config.set({
basePath: '..',
// frameworks to use
frameworks: ['mocha'],
// list of files / patterns to load in the browser
files: [
'node_modules/chai/chai.js',
'public/js/libs/jquery-1.9.1.js',
'public/js/libs/angular.js',
'test/libs/angular-mocks.js',
'public/js/**/*.js',
'test/angular/**/*.js'
],
exclude: [],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_DEBUG,
autoWatch: true,
browsers: ['Chrome'],
captureTimeout: 60000,
singleRun: false
});
};
I have a filter declared:
angular.module('timeMachine.filters',[])
.filter('hours', function() {
return function(input) {
return input == 1
? '1 hour'
: input + ' hours';
}
});
And a test:
var should = chai.should();
describe("The hours filter", function() {
beforeEach(function() {
angular.module('timeMachine.filters');
});
it('should be able to test', function(){
true.should.equal(true);
});
it('should be able to inject an hours filter', inject(function($filter) {
var hours = $filter('hours');
expect(hours).not.to.equal(null);
}));
});
However, the second test fails with the message:
[$injector:unpr] Unknown provider: hoursFilterProvider <- hoursFilter
In the context of the running Angular app this filter works.
I assume I'm missing something through inexperience and any help would be awesome!
You should be using angular.mock.module in the test.
See my answer here