How to test an Angular app? - angularjs

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...
});
});

Related

Failed to instantiate module, KARMA

I've finished to implement my web site with AngularJS and now, I must make my unit test to verify the correct functioning of my functions.
I was looking for a lot of tutorial on internet but apparently, my application structure doesn't allow testing with karma and jasmin.
Let me explain, I got a site web with just one single page HTML which is linked with one controller (a file .js) I've never installed Angular with NPM but I've imported it with:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
And I load my controller with:
<script src="main.js"></script>
and some other imported script.
I would like to try my controller with unit tests, so I've created a package.json file and installed karma, jasmine, and karma-cli with npm.
I've make a folder called "Tests" and created a test.js file:
describe("App",() =>{ //Describe object type
beforeEach(module('App')); //Load module
describe('Ctrl',()=>{
var Ctrl;
beforeEach(inject( ($injector)=>{ //instantiate controller using $controller service
$rootScope = $injector.get('$rootScope');
$controller = $injector.get('$controller');
$scope = $rootScope.$new();
}));
beforeEach(inject(($controller)=>{
Ctrl = $controller("Ctrl");
}));
it("Should say hello",()=>{
expect(Ctrl.msg).toBe("Hello");
})
})
})
But when I use:
karma start
it's doesn't detect my controller.
Here is my console output:
Here is my karma.conf.js:
// Karma configuration
// Generated on Thu Jun 14 2018 16:51:15 GMT+0200 (Paris, Madrid (heure d’été))
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/angular.js','Scripts/angular-mocks.js','main.js','Tests/*.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: {
},
// 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 simultaneous
concurrency: Infinity
})
}
And how i declare my controller :
var app = angular.module('App', ['ngMaterial', 'ngMessages'])
app.controller('Ctrl', ['$rootScope', '$scope','$http','$timeout','$mdDialog','Global', 'projects', 'screens', 'users', 'licenses', function($rootScope, $scope, $http, $timeout, $mdDialog,Global, projects, screens, users, licenses) {
...
}
Here is my tree folder :
-Root
|---node_modules
|---Tests
| |---test.js
|---Scripts
|---index.html
|---main.js <--- controller of my index.html
|---style.css
|---someFactory.js
I don't think I'm doing it in the right way. Please, explain me how to do it.

How to inject External Providers in karma jasmine test case?

I'm new to Angular and karma test cases.
For my application I'm using Angularjs and SweetAlert for displaying alerts. ( SweetAlert Plugin here )
Below is my code for getting the status for the http request and I display the http request status in SweetAlert
(function () {
'use strict';
angular
.module('app.admin')
.controller('TestController', TestController);
TestController.$inject = ['$scope','$http','SweetAlert'];
function TestController($scope,$http,SweetAlert) {
var vm = this;
vm.test = 'hi';
vm.todos = [];
vm.todo = 'Run';
vm.status = '';
vm.GetURL = function(){
$http.get("some url")
.then(function (result) {
vm.status = result.status;
SweetAlert.swal(JSON.stringify(vm.status))
});
};
vm.addTodo = function(){
vm.todos.push(vm.todo);
};
vm.removeTodo = function(index){
vm.todos.splice(index, 1);
};
}
})();
This is working fine without any problems, but I need to test my application, for that I am using karma with jasmine framework. Below is my karma.config.js and test file.
karma.config.js
// Karma configuration
// Generated on Tue Jan 26 2016 21:38: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: [
'../app/js/base.js',
'../global_URL.js',
'bower_components/sweetalert/dist/sweetalert.css',
'bower_components/sweetalert/dist/sweetalert.min.js',
'bower_components/angular-mocks/angular-mocks.js',
'../app/js/app.js',
'test/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: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
plugins: [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-phantomjs-launcher'
],
// 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
})
}
test.spec.js
'use strict';
describe('Test Controller', function () {
// load the controller's module
var MainCtrl,
SweetAlert,
URLService,
httpcall,
scope;
beforeEach(module('sample'));
/*beforeEach(inject(function(_SweetAlert_,_URLService_){
URLService = _URLService_;
SweetAlert = _SweetAlert_;
}));*/
// Initialize the controller and a mock scope
beforeEach(inject(function ($rootScope, $controller,$http,_SweetAlert_) {
scope = $rootScope.$new();
MainCtrl = $controller('TestController', {
$scope: scope,
httpcall : $http,
SweetAlert : _SweetAlert_
});
}));
it('should tell hi', function () {
expect(MainCtrl.test).toBe("hi");
});
it('should give the status', function () {
MainCtrl.GetURL();
expect(MainCtrl.status).toBe(200);
});
it('should have no items to start', function () {
expect(MainCtrl.todos.length).toBe(0);
});
it('should add items to the list', function () {
MainCtrl.todo = 'Test 1';
MainCtrl.addTodo();
expect(MainCtrl.todos.length).toBe(1);
});
it('should add then remove an item from the list', function () {
MainCtrl.todo = 'Test 1';
MainCtrl.addTodo();
MainCtrl.removeTodo(0);
expect(MainCtrl.todos.length).toBe(0);
});
});
But it throws the following error:
F:\Projects\Angular\NewSample\Development\test\master>gulp test
[13:06:40] Using gulpfile F:\Projects\Angular\NewSample\Development\test\master\gulpfile.js
[13:06:40] Starting 'test'...
WARN `start` method is deprecated since 0.13. It will be removed in 0.14. Please
use
server = new Server(config, [done])
server.start()
instead.
27 01 2016 13:06:40.250:INFO [karma]: Karma v0.13.19 server started at http://lo
calhost:9876/
27 01 2016 13:06:40.261:INFO [launcher]: Starting browser Chrome
27 01 2016 13:06:41.793:INFO [Chrome 47.0.2526 (Windows 8.1 0.0.0)]: Connected o
n socket /#hmyJFO5x2TLTkMMHAAAA with id 83740230
Chrome 47.0.2526 (Windows 8.1 0.0.0) LOG: 'localhost'
Chrome 47.0.2526 (Windows 8.1 0.0.0) LOG: 'localhost'
Chrome 47.0.2526 (Windows 8.1 0.0.0) Test Controller should tell hi FAILED
Error: [$injector:unpr] Unknown provider: SweetAlertProvider <- SweetAle
rt
http://errors.angularjs.org/1.4.2/$injector/unpr?p0=SweetAlertProvider%2
0%3C-%20SweetAlert
at F:/Projects/Angular/NewSample/Development/test/ap
p/js/base.js:9274:12
I don't know why., How can i solve this?
For this i take long week, is it possible to include third party plugins in karma.
Please help me, Thanks in advance.
Before inject you should add this line.
beforeEach(module('_SweetAlert_'));
And also change karma.config.js file path like below.
bower_components/sweetalert/dist/sweetalert.min.js to app/bower_components/sweetalert/dist/sweetalert.min.js
Try this.(Here I have used $injector to inject the SweetAlert)
describe('Test Controller', function () {
var MainCtrl,
SweetAlert,
URLService,
httpcall,
scope;
beforeEach(module('sample'));
beforeEach(module('SweetAlert'));
beforeEach(inject(function ($injector) {
$rootScope = $injector.get('$rootScope');
$scope = $rootScope.$new();
SweetAlert = $injector.get('SweetAlert');
MainCtrl = $controller('TestController', {
$scope: scope,
httpcall : $http,
SweetAlert : SweetAlert
});
}));
});

ngStorage breaking my application tests

I have an Angular app with a simple karma test and a very simple configuration using requirejs and Angular 1.2.28. My test is ok.
/**
* Created by jose on 7/12/2015.
*/
/*global module, inject */
define(['home', 'angularMocks','ngStorage'], function(app) {
'use strict';
describe('homeController', function () {
var scope, $location, createController;
beforeEach(module('homeApp'));
beforeEach(inject(function ($rootScope, $controller, _$location_) {
$location = _$location_;
scope = $rootScope.$new();
createController = function () {
return $controller('homeController', {
'$scope': scope
});
};
}));
it('should have message', function () {
var controller = createController();
$location.path('/');
expect($location.path()).toBe('/');
expect(scope.message).toEqual('This is Add new order screen');
});
});
});
My module:
/**
* Created by jose on 7/12/2015.
*/
'use strict';
define(['angular', 'angularRoute'], function(angular) {
var app = angular.module('homeApp', ['ngRoute']);
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'partials/home.html',
controller: 'homeController'
})
.when('/404', {
templateUrl: 'partials/404.html',
})
.otherwise({
redirectTo: '/404'
});
}
]);
app.controller('homeController', function ($scope) {
$scope.message = 'This is Add new order screen';
});
return app;
});
Unfortunately, when I try to add ngStorage as a dependency for this module, it cannot works anymore. Even try to add ngStorage to my karma configuration raise an error like this:
Error: Mismatched anonymous define() module: function (app) {
It only happens when I try to use ngStorage, when I just comment it into my karma.conf file error disappears and everything works fine...
In case of not being possible using ngStorage with Karma there are another alternatives for ngStorage? thanks
karma.conf
// Karma configuration
// Generated on Mon Jul 13 2015 09:49:28 GMT-0300 (Hora est. Sudamérica Pacífico)
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-main.js',
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-route/angular-route.js',
'bower_components/ngstorage/ngStorage.js',
{pattern: 'javascripts/*.js', included: false},
{pattern: 'test/**/*Spec.js', included: false}
],
// list of files to exclude
exclude: [
'javascripts/config.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_DEBUG,
// 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
});
};
Project is at github: https://github.com/jbarros35/node/tree/master/angulartemplate
kind regards.
It appears as though you are not the only one receiving errors trying to use Karma and ngStorage together. The guys at Karma have made some of their code available to help resolve the issue. You can check it out here:
https://github.com/gsklee/ngStorage/issues/117
If you look at the code of ngStorage you'll see that it calls define. So it is a proper AMD modules. Each AMD module you use in a Karma setup must be loaded with included: False in files:
{ pattern: 'bower_components/ngstorage/ngStorage.js', included: False }
Otherwise, Karma will load it with a script element, and you will get the error you got.
It's because of the async load feature of require js. Errors can be solved by this way
Go to the test-main.js.
add shim there in this way
shim:{
'yourJsModule':{
deps:['angular','yourApp']
}
}
replace "yourJsModule" with the your angular file you intend to test and the 'yourApp' with your angular module file...

Unit testing using Jasmine and Karma / AngularJS project

I am writing test cases using AngularJS with Jamsine. Working on mobile application using AngularJS and for UI using IONIC framework. So I am calling one of controller function from my spec.js for testing. Meantime, I am getting error like.
Error: Unexpected request: GET ./partials/main.html
No more request exceepted
This is my mail html file. In main.html file we are loading all other states of application.
And I already injected html in spec.js. See below code.
beforeEach(inject(function ($rootScope, $controller, $q,$injector) {
$httpBackend = $injector.get('$httpBackend');
$httpBackend.whenGET('./partials/main.html').respond(200, '');
}));
Still i ma not able to resolve error. Can i add those html files in 'spec.js' ? or any other solution ? Please help me. I am a fresher with Karma and Jasmine.
Thanks in advance.
Change your code to expectGET in place of whenGET like this
beforeEach(inject(function ($rootScope, $controller, $q,$injector) {
$httpBackend = $injector.get('$httpBackend');
$httpBackend.expectGET('./partials/main.html').respond(200);
}));
Yes Keshav. Please see below code :
Below is my karma.conf.js file. Here are all files added which I need to test. And as well as I have added a few plugins for generating reports and code coverage.
module.exports = function(config) {
config.set({
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
plugins: [
'karma-jasmine',
'karma-coverage',
'karma-chrome-launcher',
'karma-html-reporter',
'karma-ng-html2js-preprocessor'
],
// list of files / patterns to load in the browser
files: [
'my_dir_path/www/js/libs/angular.js',
'my_dir_path/www/js/libs/angular-mocks.js',
'my_dir_path/www/js/libs/ionic.js',
'my_dir_path/www/js/libs/angular.min.js',
'my_dir_path/www/js/libs/angular-route.js',
'my_dir_path/www/js/libs/angular-sanitize.js',
'my_dir_path/www/js/libs/angular-animate.js',
'my_dir_path/www/js/libs/angular-touch.min.js',
'my_dir_path/www/js/libs/angular-ui-router.js',
'my_dir_path/www/js/libs/ionic-angular.js',
'my_dir_path/www/js/libs/http-auth-interceptor.js',
'my_dir_path/www/js/libs/ng-map.min.js',
'my_dir_path/www/js/index.js',
'my_dir_path/www/js/app.js',
'my_dir_path/www/js/controllers.js',
'my_dir_path/www/js/services.js',
'my_dir_path/www/js/startSpec.js',
'*.html'
],
// 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: {
//'**/*.html': ['angular-templating-html2js']
"my_dir_path/www/partials/*.html": ["ng-html2js"]
},
ngHtml2JsPreprocessor: {
// If your build process changes the path to your templates,
// use stripPrefix and prependPrefix to adjust it.
//stripPrefix: "source/path/to/templates/.*/",
//prependPrefix: "web/path/to/templates/",
stripPrefix:"my_dir_path/www/",
// the name of the Angular module to create
moduleName: 'partials'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'html'],
// the default configuration
/* htmlReporter: {
outputDir: 'karma_html',
templatePath: 'node_modules/karma-html-reporter/jasmine_template.html'
}, */
// 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
});
};
And this is my spec.js file. Here I am writing unit test cases for the controller. In this specs calling function "$scope.onClickResetForgot()" (That is in controller) for testing controller code. In controller I am also calling one HTTP service. After HTTP call, we are not able to back in response that why we have updating scope manually via $scope.$digest().
'use strict';
describe('loginController', function () {
var $scope,$controller,$httpBackend, AuthenticationService, def, respData = {data : {Success:true,ErrorMsg:""}};
beforeEach(inject(function ($rootScope, $controller, $q,$injector) {
$httpBackend = $injector.get('$httpBackend');
$httpBackend.expectGET('./partials/main.html').respond(200);
AuthenticationService = {
forgotPassword: function (data) {
console.log(data);
def = $q.defer();
return def.promise;
}
};
spyOn(AuthenticationService, 'forgotPassword').and.callThrough();
$scope = $rootScope.$new();
$controller = $controller('loginController', {
'$scope': $scope,
AuthenticationService : AuthenticationService
});
}));
it("Verifying login credentials, device token and device id." , function() {
$scope.Reset.Email = "harish.patidar#gmail.com";
$scope.onClickResetForgot();
def.resolve(respData);
// Update response to controller. So we need to call below line manually.
$scope.$digest();
expect(AuthenticationService.forgotPassword).toHaveBeenCalled();
$httpBackend.flush();
})
});
});
And this is my controller in controller.js.
.controller('loginController', ['$rootScope', '$scope', '$http', '$state', 'AuthenticationService', '$ionicPopup', function($rootScope, $scope, $http, $state, AuthenticationService,$ionicPopup) {
$scope.onClickResetForgot =function(type) {
console.log($scope.Reset.Email);
$scope.forgotMessage = "";
$rootScope.message = "";
AuthenticationService.forgotPassword({"Email": $scope.Reset.Email}).then(function (resp) {
var forgotPasswordPopup = $ionicPopup.alert({
title: "Forgot Password",
template: "An email has been sent to '"+$scope.Reset.Email+"' with instructions for recovering your AlertSense credentials"
});
forgotPasswordPopup.then(function(res) {
$scope.onCancelForgot();
});
});
}
}])
So after updating scope to controller, I am getting error as mentioned above. Please let me know if you need more information.

Scope variables undefined when testing controller with Karma and Jasmine with ng-scenario as framework

I've just started to discover angular unit testing mysteries using Karma & Jasmine and I have some problems with controllers tests. I've wrote tests to see if variables are defined: expect(scope.someVariable).toBeDefined(). Everything worked as expected ( every test was successfully ) untill I've added ng-scenario in karma.conf.js file.
I'm using node to run tests.
Problem: After adding ng-scenario in karma configuration file as framework all tests for checking if scope variables are defined are failing. Before adding ng-scenario all tests were successfully. Do you have any ideea why is this happening ?
Karma Conf file:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['ng-scenario','jasmine'],
files: [ 'app/plugins/jquery/jquery.js',
'app/plugins/angular/angular.js', 'app/plugins/angular-scenario/angular-scenario.js',
'app/plugins/angular-mocks/angular-mocks.js',
'app/plugins/angular-resource/angular-resource.js',
'app/plugins/angular-cookies/angular-cookies.js',
'app/plugins/angular-sanitize/angular-sanitize.js',
'app/plugins/angular-route/angular-route.js', 'app/plugins/angular-utf8-base64/angular-utf8-base64.js',
'app/scripts/*.js',
'app/scripts/**/*.js',
'test/**/*.js',
'app/views/templates/*.html'
],
preprocessors : { 'app/views/templates/*.html': 'html2js' },
exclude: ['app/plugins/angular-scenario/angular-scenario.js'],
port: 8080,
logLevel: config.LOG_INFO,
autoWatch: false,
browsers: ['Chrome'],
singleRun: false }); };
Controller test:
'use strict'
describe('Controller: MainCtrl', function () {
beforeEach(module('qunizGameApp'));
var MainCtrl,scope, configService,feedbackService,authService,notify,resourceService;
beforeEach(inject(function ($controller, $rootScope,_configService_,_feedbackService_, _authService_,_notify_, _resourceService_) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope,
configService:_configService_,
feedbackService:_feedbackService_,
authService:_authService_,
notify:_notify_,
resourceService:_resourceService_
});
configService=_configService_;
feedbackService=_feedbackService_;
authService=_authService_;
notify=_notify_;
resourceService=_resourceService_; }));
it('should be defined -configService', function () {
expect(scope.configService).toBeDefined();
});
it('should be defined - resourceService', function () {
expect(scope.resourceService).toBeDefined();
});
it('should be defined - sidebarVisible', function () {
expect(scope.sidebarVisible).toBeDefined(); });
});
Proof of working test before including ng-scenario:
Proof of failure test after including ng-scenario:
And a wierd thing is that if I debug the test in my chrome console, variables are defined:
Things read on interned and tried:
1.I've tried to define variables on scope in beforeEach section as a mock data.
2.I've tried to inject all other controller dependencies ( with undescored name as paramaters)
You can see 1 and 2 below
beforeEach(inject(function ($controller, $rootScope,_configService_,_feedbackService_, _authService_,_notify_, _resourceService_) {
scope = $rootScope.$new();
scope.configService=_configService_;
scope.authService=_authService_;
scope.resourceService=_resourceService_;
scope.sidebarVisible={};
MainCtrl = $controller('MainCtrl', {
$scope: scope,
configService:_configService_,
feedbackService:_feedbackService_,
authService:_authService_,
notify:_notify_,
resourceService:_resourceService_
});
configService=_configService_;
feedbackService=_feedbackService_;
authService=_authService_;
notify=_notify_;
resourceService=_resourceService_; }));
But scope.configService, scope.resourceService and scope.sidebarVisible are still undefined at the moment of test
I had the same problems with ng-scenario when using it with Karma. The moment I included it in karma.conf.js file, none of my tests was passing. Just don't use ng-scenario - use Protractor for integration testing. https://github.com/angular/protractor

Resources