I'm learning AJS unit testing, with RequireJS, Karma, Mocha, Chai and angular-mocks. I've had some luck with the first four, but need to get into "real" testing and can't get angular-mocks to work. There's a lot going on, so I'll be as succinct as possible.
test/karma.conf.js
module.exports = function (config) {
config.set({
// requirejs may need to be listed before other modules (see https://github.com/princed/karma-chai-plugins#limited-requirejs-support)
frameworks: ["requirejs", "mocha", "chai"],
files: [
// load the RequireJS config files first
{pattern: "client/app/require-shared.js", watched: false},
{pattern: "test/require-test.js", watched: false},
// set included to false for files to be loaded via RequireJS
{pattern: "client/**/*.js", included: false },
{pattern: "bower_components/**/*.js", included: false, watched: false},
// Mocha stuff
{pattern: "test/unit/mocha.conf.js", watched: false},
// test files
{pattern: "test/unit/**/pageSelectorTest.js", included: false }
],
exclude: [
"client/app/bootstrap.js",
"client/app/require-main.js",
"*.conf.js"
],
reporters: ["spec"],
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
browsers: [
"PhantomJS"
],
singleRun: true
});
};
test/unit/mocha.conf.js
window.mocha.setup({
ui: "tdd"
});
test/unit/MyTest.js
define([
"angular-mocks"
,"app"
], function () {
"use strict";
var MODULE_NAME = "PageSelector";
var assert = chai.assert;
suite("Unit testing " + MODULE_NAME, function() {
suite(MODULE_NAME + " module", function () {
var appModule;
setup(function () {
// "ng" and "ngMock" modules automatically loaded
appModule = angular.mock.module(MODULE_NAME);
console.log(appModule);
});
// setup(function () {
// angular.mock.inject(function () {
//
// });
// });
test("should exist", function () {
assert.isDefined(appModule, "module exists");
});
}); // end module tests
});
});
I'll skip posting all the RequireJS config. I'm pretty sure I'm getting angular and angular-mocks, because I've worked through those errors already.
My Gruntfile simply has an option to load karma.conf.js. The output of grunt karma is:
Running "karma:unit" (karma) task
INFO [karma]: Karma v0.12.16 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.7 (Linux)]: Connected on socket WJUF8xogEo-XCG-8zzJX with id 10483911
PhantomJS 1.9.7 (Linux)
LOG LOG: undefined
Unit testing PageSelector
PageSelector module
✗ should exist
AssertionError: module exists: expected undefined to not equal undefined
at /home/client/node_modules/chai/chai.js:925
at assertEqual (/home/client/node_modules/chai/chai.js:1402)
at /home/client/node_modules/chai/chai.js:3627
at /home/client/node_modules/chai/chai.js:2648
at /home/client/test/unit/utility/pageSelectorTest.js:37
at callFn (/home/client/node_modules/mocha/mocha.js:4338)
at /home/client/node_modules/mocha/mocha.js:4331
at /home/client/node_modules/mocha/mocha.js:4728
at /home/client/node_modules/mocha/mocha.js:4819
at next (/home/client/node_modules/mocha/mocha.js:4653)
at /home/client/node_modules/mocha/mocha.js:4663
at next (/home/client/node_modules/mocha/mocha.js:4601)
at /home/client/node_modules/mocha/mocha.js:4625
at done (/home/client/node_modules/mocha/mocha.js:4300)
at callFn (/home/client/node_modules/mocha/mocha.js:4343)
at /home/client/node_modules/mocha/mocha.js:4331
at next (/home/client/node_modules/mocha/mocha.js:4626)
at /home/client/node_modules/mocha/mocha.js:4625
at done (/home/client/node_modules/mocha/mocha.js:4300)
at callFn (/home/client/node_modules/mocha/mocha.js:4343)
at /home/client/node_modules/mocha/mocha.js:4331
at next (/home/client/node_modules/mocha/mocha.js:4626)
at /home/client/node_modules/mocha/mocha.js:4630
at timeslice (/home/client/node_modules/mocha/mocha.js:5763)
PhantomJS 1.9.7 (Linux): Executed 1 of 1 (1 FAILED) ERROR (0.003 secs / 0.002 secs)
Warning: Task "karma:unit" failed. Use --force to continue.
Aborted due to warnings.
If I change angular.mock.module(MODULE_NAME); to angular.module(MODULE_NAME);, the assert works. What am I missing? (I apologize if there isn't enough info above. I can post more, as needed.)
I dug into angular-mocks.js. module is just a set-up for inject. On its own, it doesn't actually load a module, like angular.module does. I was using it unnecessarily for "module-level" testing, where angular.module is appropriate.
When getting in to actual controller/directive/etc. testing, I'll need the module+inject pair.
Related
I want just run karma test inside a template called Clip-two.
when i start karma conf
karma start my.conf.js
this is my error:
25 05 2017 11:36:10.911:WARN [karma]: No captured browser, open http://localhost:9876/
Chrome 49.0.2623 (Mac OS X 10.7.5) Users factory should exist FAILED
Error: [$injector:modulerr] http://errors.angularjs.org/1.4.7/$injector/modulerr?p0=clip-two&p1=Error%3A%20%5B%24injector%3Amodulerr%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.4.7%2F%24injector%2Fmodulerr%3Fp0%3DngCookies%26p1%3DError%253A%2520%255B%2524injector%253Anomod%255D%2520http%253A%252F%252Ferrors.angularjs.org%252F1.4.7%252F%2524injector%252Fnomod%253Fp0%253DngCookies%250A%2520%2520%2520%2520at%2520Error%2520(native)%250A%2520%2520%2520%2520at%2520http%253A%252F%252Flocalhost%253A9876%252Fbase%252Fbower_components%252Fangular%252Fangular.min.js%253Fb6b56d0e096efc26e09d6...cc346%3A41%3A35)%0A%20%20%20%20at%20Object.workFn%20(http%3A%2F%2Flocalhost%3A9876%2Fbase%2Fbower_components%2Fangular-mocks%2Fangular-mocks.js%3Fe9f36bdb59779aa33da5eab3dfd5ffda120d58aa%3A2427%3A52)
my karma confs is made by karma init command. I added all files only
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
angular: ['mocks'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.min.js',
'bower_components/angular-animate/angular-animate.min.js',
'bower_components/angular-touch/angular-touch.min.js',
'bower_components/angular-sanitize/angular-sanitize.min.js',
'bower_components/angular-ui-router/release/angular-ui-router.min.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/ngstorage/ngStorage.min.js',
'bower_components/angular-translate/angular-translate.min.js',
'bower_components/angular-translate-loader-url/angular-translate-loader-url.min.js',
'bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.min.js',
'bower_components/angular-translate-storage-local/angular-translate-storage-local.min.js',
'bower_components/angular-translate-storage-cookie/angular-translate-storage-cookie.min.js',
'bower_components/oclazyload/dist/ocLazyLoad.min.js',
'bower_components/angular-breadcrumb/dist/angular-breadcrumb.min.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js',
'bower_components/angular-loading-bar/build/loading-bar.min.js',
'bower_components/angular-scroll/angular-scroll.min.js',
'STANDARD/assets/js/app.js',
'STANDARD/assets/js/main.js',
'STANDARD/assets/js/config.constant.js',
'STANDARD/assets/js/config.router.js',
'STANDARD/assets/js/services/agente.js',
'STANDARD/assets/js/controllers/inboxCtrl.js',
'STANDARD/assets/test/*.js'
],
exclude: [
],
preprocessors: {
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_WARN,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
}
this is my unit test
describe('Users factory', function() {
// Before each test load our api.users module
beforeEach(module('clip-two'));
// Before each test set our injected Users factory (_Users_) to our local Users variable
var $controller;
beforeEach(angular.mock.inject(function(_$controller_){
$controller = _$controller_;
}));
// A simple test to verify the Users factory exists
it('should exist', function() {
expect($controller).toBeDefined();
});
});
and that my app.js
'use strict';
angular.module("clip-two", [
'ngAnimate',
'ngCookies',
'ngStorage',
'ngSanitize',
'ngTouch',
'ui.router',
'ui.bootstrap',
'oc.lazyLoad',
'cfp.loadingBar',
'ncy-angular-breadcrumb',
'duScroll',
'pascalprecht.translate',
]);
some advice?
The error says that there is a problem with ngCookies in your test.
And when I look at your karma conf file, I can't see the file containing ngcookies loaded.
You probably just need to add it in karma.conf to make it work.
Considering the error, it seems that when running karma, the host can't be reached.
Can you access your application through http://localhost:9876/?
You may try to run them again keeping your browser opened on the above address, I know it seems that it doesn't make sense, but on some systems this fixes the issue.
Then taking a look at your karma file, maybe there are some dependencies missing. Be sure that you are including all the files you need, otherwise also when your tests will run, you may have few failures.
But I can understand that now the important is that tests run :D
I am trying to test directive in angular using Jasmine. I installed karma-ng-html2js-preprocessor using NPM. Then I istalled jQuery using Bower but I am getting this error
Connected on socket ndfTI8XJInIU5YJCAAAA with id 49983199
Chrome 47.0.2526 (Mac OS X 10.10.2) http controller test it should be one FAILED
Error: [$injector:modulerr] Failed to instantiate module templates due to:
Error: [$injector:nomod] Module 'templates' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.4.8/$injector/nomod?p0=templates
at /Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:68:12
at /Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:2005:17
at ensure (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:1929:38)
at module (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:2003:14)
at /Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/a
I made directive like this
angular.module('app',[]).controller('first',function($scope,data){
$scope.name='test';
$scope.message='application';
data.getData().then(function(data){
console.log(data);
})
}).factory('data',function($http){
return{
getData:getData
}
function getData(){
return $http.get('data.json').success(successCall).error(errorcallback)
}
function successCall(data){
return data
}
function errorcallback(data){
return data
}
}).directive('helloWorld',function(){
return {
restrict:'E',
scope:{
data:'=',
message:'#'
} ,
templateUrl:'app/partial/home.html',
link:function(s,e,a){
}
}
})
home.html
<div class="dir">
<h1>{{data}}</h1>
<h1>{{message}}</h1>
</div>
test.js
describe('http controller test', function () {
var $rootScope,
$scope,
$compile,
$body=$('body'),
el,
$el,
controller,
html='<hello-world data="name" message="{{message}}"></hello-world>';
beforeEach(function(){
module('templates','app') ;
inject(function($injector){
$rootScope = $injector.get('$rootScope') ;
$compile = $injector.get('$compile') ;
$scope=$rootScope.$new();
el=$compile(angular.element(html))($scope)
controller =$injector.get('$controller')('first',{$scope:$scope})
})
$body.append(el);
$rootScope.$digest();
$el=$('.dir');
})
afterEach(function(){
$body.empty();
})
it('it should be one',function(){
expect($el.length).isEqual(1)
})
describe('Init value',function(){
it('check name value',function(){
expect($scope.name).toEqual('test');
})
})
it('it should be true',function(){
expect(true).toBeTruthy();
})
})
and there is karma-config file
// Karma configuration
// Generated on Fri Dec 18 2015 19:53:32 GMT+0530 (IST)
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: [
'bower_components/angular/angular.js' ,
'bower_components/jquery/dist/jquery.js' ,
'bower_components/angular-mocks/angular-mocks.js' ,
'bower_components/angular-resource/angular-resource.js' ,
'app/**/.html',
'app/*.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: {
'app/**/.html':['ng-html2js']
},
ngHtml2JsPreprocessor:{
moduleName:'templates'
},
// 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,
// Concurrency level
// how many browser should be started simultanous
concurrency: Infinity
})
}
I already declared the template module like this
ngHtml2JsPreprocessor:{
moduleName:'templates'
},
update 1
Connected on socket i5kkzULDwF1_ptvcAAAA with id 55433592
Chrome 47.0.2526 (Mac OS X 10.10.2) http controller test it should be one FAILED
Error: [$injector:modulerr] Failed to instantiate module templates due to:
Error: [$injector:nomod] Module 'templates' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.4.8/$injector/nomod?p0=templates
at /Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:68:12
at /Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:2005:17
at ensure (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:1929:38)
at module (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:2003:14)
at /Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:4435:22
at forEach (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:340:20)
at loadModules (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:4419:5)
at Object.createInjector [as injector] (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular/angular.js:4344:11)
at Object.workFn (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular-mocks/angular-mocks.js:2428:52)
at window.inject.angular.mock.inject (/Users/naveenkumar/Documents/ionic_work/tes/bower_components/angular-mocks/angular-mocks.js:2411:37)
http://errors.angularjs.org/1.4.8/$injector/modulerr?p0=templates&p1=Error%3A%20%5B%24injector%3Anomod%5D%20Module%20'templates'%20is%20not%20available!%20You%20either%20misspelled%20the%20module%20name%20or%20forgot%20to%20load%20it.%20If%
I have no prior experiences with karma-ng-html2js-preprocessor so this is more like a guess - could it be that template module was not generated because no templates were found.
Could you try to change this part of files section of your karma-config from:
'app/**/.html'
to:
'app/**/*.html'
and preprocessors section from:
preprocessors: {
'app/**/.html':['ng-html2js']
}
to
preprocessors: {
'app/**/*.html':['ng-html2js']
}
Update:
If that doesn't work for you, you could set log level of Karma to
logLevel: config.LOG_DEBUG
and try to search for lines starting with DEBUG [preprocessor.html2js] to gather additional info related to html2js preprocessor.
I am trying to do testing using jasmine .When I run this command karma start karma.conf.js it give me this error.
Chrome 47.0.2526 (Windows 7 0.0.0) Firstcontroller Initialization title should be naveen FAILED
Error: [$injector:modulerr] Failed to instantiate module app due to:
Error: [$injector:nomod] Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the depend
encies as the second argument.
http://errors.angularjs.org/1.4.8/$injector/nomod?p0=app
at D:/Webapplication/karmaTest/bower_components/angular/angular.js:68:12
at D:/Webapplication/karmaTest/bower_components/angular/angular.js:2005:17
at ensure (D:/Webapplication/karmaTest/bower_components/angular/angular.js:1929:38)
at module (D:/Webapplication/karmaTest/bower_components/angular/angular.js:2003:14)
at D:/Webapplication/karmaTest/bower_components/angular/angular.js:4435:22
at forEach (D:/Webapplication/karmaTest/bower_components/angular/angular.js:340:20)
at loadModules (D:/Webapplication/karmaTest/bower_components/angular/angular.js:4419:5)
at Object.createInjector [as injector] (D:/Webapplication/karmaTest/bower_components/angular/angular.js:4344:11)
at Object.workFn (D:/Webapplication/karmaTest/bower_components/angular-mocks/angular-mocks.js:2428:52)
at window.inject.angular.mock.inject (D:/Webapplication/karmaTest/bower_components/angular-mocks/angular-mocks.js:2411:37)
I install karma , karma-jasmine ,karma-chrome launcher ..When I run simple test like expect(true).toBeTruthy it works fine.But when I am trying to test my controller .it gives me above error .
here is my controller
//(function () {
// 'use strict';
//
// angular.module('app',[]).controller('FirstController',FirstController);
//
// FirstController.$inject=['$scope']
//
// function FirstController($scope){
// $scope.title='naveen';
// }
//
//})();
angular.module('app',[]).controller('FirstController',FirstController);
FirstController.$inject=['$scope'];
function FirstController($scope){
$scope.title='naveen';
}
here is my test-spec.js file
describe('Firstcontroller', function () {
var $rootScope,
$scope,
controller;
beforeEach(function () {
module('app');
inject(function ($injector) {
$rootScope = $injector.get('$rootScope');
$scope=$rootScope.$new();
console.log('==========================')
controller=$injector.get('$controller')('FirstController',{$scope:$scope});
})
})
describe('Initialization',function(){
it('title should be naveen',function(){
expect($scope.title).toEqual('naveen')
})
})
})
it give be above error why ?
I include the package in karma.config file
karma.config file
// Karma configuration
// Generated on Tue Dec 08 2015 18:55:16 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: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'app/**/.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: ['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
})
}
update
I insert my js file inside the app directory when I change this 'app/**/.js' to 'app/*.js' it works fine ..why it works ?
Module 'app' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
The module in your Angular code is 'apps' not 'app'.
Fix the spelling mistake and it should work.
Okay, so I have a seed setup and I have Jasmin Running (Thank you so much SoEzPz for the help).
it appears my spec's won't run, I tried and isolated spec and it ran with no issue but when I try to write one on a controller it errors.
here is the controller.
//This is the about function that is used in the About Module.
'use strict';
app.controller('AboutController',// jshint ignore:line
['$scope',
function ($scope) {
$scope.message = 'This is the about page message from the controller';
}]);
a very basic controller
here is my test
'use strict';
describe('Controller: com/modules/AboutController', function() {
beforeEach(module('app'));
var AboutController,
scope;
beforeEach(inject(function ($rootScope, $controller) {
scope = $rootScope.$new();
AboutController = $controller('AboutController', {
$scope: scope
});
}));
it('It should show the page message', function () {
expect(scope.greeting).toEqual("This is the about page message from the controller");
});
});
The spec returns this error
ReferenceError: module is not defined
at Suite.<anonymous> (http://localhost:8888/com/modules/about/aboutController_spec.js:5:16)
at addSpecsToSuite (http://localhost:8888/:801:25)
at Env.describe (http://localhost:8888/:771:7)
at jasmineInterface.describe (http://localhost:8888/:3277:18)
at http://localhost:8888/com/modules/about/aboutController_spec.js:3:1
am I missing something or is my spec written wrong ?
I am including the ngmock here is my Karma.conf file
// Karma configuration
// Generated on Tue Jul 28 2015 11:28:22 GMT-0400 (EDT)
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: [
'../src/lib/js/angular/angular.min.js',
'../src/lib/js/angular/angular-mocks.js',
'../src/com/**/*.js',
'../src/com/**/*_spec.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'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
})
}
This was definitely deceptive, after playing around with the specs (thinking that the issue was in the actual specifications ) I found a test that ran fine, but still my other specs would not run, so what I did was I went back and took a hard look at my karma.conf file and while looking through some of the other examples I found I wasn't including enough in the way of bower components. so I added some more IE resources, cookies ect and low and behold all tests passed .
here is what I added under files for those who might be having the same issue
'bower_components/angular/angular.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'../src/com/**/*.js',
'../src/com/**/*_spec.js'
For simple application such as just a "Hello World" where do I write tests.
I have created a plnkr.
http://plnkr.co/edit/M0GAIE837G3s1vNwTyK8?p=info
Now this is a very simple plnkr, which does nothing but display Hello World.
Now if I want to write a test for this Application i.e for MainCtrl.. where do I plug it in ?
To run test with Angular-Karma-Jasmine:
You need to install nodejs, karma runs on top of node
You need to install karma from Node Packaged Modules from your command window execute: npm install -g karma
If you plan to run this with Chrome and Firefox and you are running this on windows you need to add 2 environment variables:
CHROME_BIN = [Crome installation path/chrome.exe]
FIREFOX_BIN =[Firefox installation path/firefox.exe]
4. Go back to your project folder using the command window once there you can execute:karma init
Just hit enter until it finishes; bottom line this will create a file named: karma.config.js
In my project this file looks like this, yours probably will include some helpful comments on the different settings:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'../app/*.js',
'../app/lib/angular.js',
'../app/lib/angular-route.min.js',
'../app/lib/angular-mocks.js',
'../app/app.js',
'controllers/*.js',
'services/*.js',
],
exclude: [
],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome','Firefox'],
captureTimeout: 60000,
singleRun: false
});
};
Important: make sure you included angular-mocks in your configuration, the inject function is on that module.
5. Go back to your command window, navigate where your karma.config.js file is and and execute: karma start
At this point you will be good to go to start writing tests with jasmine.
a simple jasmine test for your controller will be:
describe('MainCtrl', function() {
var $scope, $rootScope, createController;
beforeEach(inject(function($injector) {
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
var $controller = $injector.get('$controller');
createController = function() {
return $controller('MainCtrl', {
'$scope': $scope
});
};
}));
it('should have a...', function() {
var controller = createController();
// do your testing here...
});
});