Error: Argument 'Ctrl' is not a function, got undefined unit testing - unit-testing

I'm having a hard time figuring this out. I'm starting to build my testscript. Even though its a little late. But unit testing is a good practice. For a start I just want to test two scope model (scope.global & scope.security) but I got a weird error saying my MainCtrl is not a function?
'use strict';
/* Controllers */
angular.module('mainCtrl', ['LocalStorageModule'])
.controller('MainCtrl', ['$scope' ,'$rootScope', '$location', 'Api', 'Security', 'Utils', 'localStorageService',function (scope, rootScope, location, Api, Security, Utils, session) {
console.log('main js loaded');
// $scope.main = {};
scope.global = {};
scope.security = Security;
....
}]);
My controllerSpec.js
describe('controllers MainCtrl', function(){
beforeEach(function(){
module('Services.api'),
module('LocalStorageModule')
});
describe('MainCtrl', function() {
var scope, api, security, session;
beforeEach(inject(function($rootScope, $controller ,$location, Api, localStorageService){
scope = $rootScope.$new();
$location = $location;
$controller("MainCtrl", {
$scope : scope,
localStorageService : localStorageService,
Api : Api
});
}));
it('should create "usertype" model with empty list', function(){
expect(scope.global).toBe(undefined);
});
});
});
Error result from above code:
Chrome 24.0 (Linux) controllers MainCtrl MainCtrl should create "usertype" model with empty list FAILED
Error: Argument 'MainCtrl' is not a function, got undefined
I've tested my webapp on a browser and it doesn't encounter this MainCtrl is not function.
Please help.

Is this correct?
angular.module('mainCtrl', ['LocalStorageModule'])
It seems like the module should be named something other than mainCtrl since that is what your controller is named.
In your test, you are not loading the module:
beforeEach(function(){
module('Services.api'),
module('LocalStorageModule')
});

Related

Test Angular controller with Protractor

This is example of my code:
describe('myCtrl functionality', function() {
var driver;
var ptor;
beforeEach(function() {
ptor = protractor.getInstance();
ptor.ignoreSynchronization = true;
browser.ignoreSynchronization = false;
driver = ptor.driver;
});
it('should login', function() {
driver.get('someurl');
driver.findElement(protractor.By.name('username')).sendKeys('admin');
driver.findElement(protractor.By.name('password')).sendKeys('admin');
driver.findElement(protractor.By.css('button[type="submit"]')).click();
});
describe('myCtrl testing', function() {
var $scope;
beforeEach(module('myApp'));
beforeEach(inject(function($rootScope, $controller) {
$scope = $rootScope.$new();
$controller('dashStoresCtrl', {$scope: $scope});
}));
it('should create "stores" model', function() {
var containerStores = element(by.css('.dashboardStores'));
containerStores.findElements(by.css('.store-item-holder')).then(function(elems) {
expect(elems.length).toEqual($scope.stores.length);
});
});
});
});
And the problem is when i run tests i get TypeError: object is not a function.
That is for the line beforeEach(module('myApp'));
I made research and find out that i need to include angular-mocks.js file in my project and in index.html.
I did it but still get TypeError: object is not a function.
Anyone who can help with this?
Thanks!!!
Protractor tests are end-to-end tests, where NodeJS executes tests that connect to your browser and use it like a numan being would do.
You're trying, in such a protractor test, to use the angularJS API and modules to unit-test a controller. That doesn't make much sense.
Unit tests are typically executed by Karma, inside your browser, and end-to-end protractor tests are typically executed using protractor, inside NodeJS. You shouldn't have a unit test and a protractor test in the same file.

Angularjs - how to correctly replace service dependency with a mock

I'm using yeoman generator created app, and doing my tests in karma.
I have reusable mock objects for every of my service.
How do i correctly replace specific service dependcy with a mock, so i could then use jasmine to spy upon methods
So far i have done like this:
My service:
angular.module('ql')
.service('loginService', ['$http','API','authService', function ($http, API, authService) {
return {
//service implementation
}]);
Mock of authService:
'use strict';
//lets mock http auth service, so it would be spied upon.
ql.mock.$authServiceMockProvider = function() {
this.$get = function() {
var $service = {
loginConfirmed: function() { }
};
return $service;
};
};
//and register it.
angular.module('qlMock').provider({
$authServiceMock: ql.mock.$authServiceMockProvider
});
And my test:
'use strict';
describe('When i call login method()', function () {
// load the service's module
beforeEach(module('ql'));
beforeEach(angular.mock.module('qlMock'));
// instantiate service
var loginService,
authService,
$httpBackend;
beforeEach(function() {
// replace auth service with a mock.
// this seems kind of dirty... is there a bettery way?
module(function($provide, $injector){
authService = $injector.get('$authServiceMockProvider').$get();
$provide.value('authService', authService);
});
//actually get the loginService
/*jshint camelcase: false */
inject(function(_loginService_, _$httpBackend_) {
loginService = _loginService_;
$httpBackend =_$httpBackend_;
});
//http auth module method, that should be call only on success scenarios
spyOn(authService, 'loginConfirmed').andCallThrough();
});
it('it should do something', function () {
//actual test logic
});
});
What i do not like is the line:
authService = $injector.get('$authServiceMockProvider').$get();
I would like to simply somehow get the authServiceMock (without getting provider, and calling et method) and then inject it into loginService.
I know i could call my $authServiceMock simply authService, and provide it as a mock, so that it would always override my default implementation, but i do not want to do this.
I know this is late but maybe it will help someone who happen upon this post.
Mocking a service in Jasmine is quite simple using Angular's $provide service. The trick is to use $provide to swap out a service implementation before injecting the service.
For example let's say we are testing a service that makes use of the $location service to get information about the current URL.
// load the service's module under test
beforeEach(module('myExampleModule'));
// mock out $location with a fake one
beforeEach(module(function ($provide) {
//create mock impl
var mockLocation = {
path: function(){
return '/somewhere'
}
}
$provide.value('$location', mockLocation); // use $provide to swap the real $location with our mock
}));
var $location;
// inject dependencies ($location will be our mocked $location)
beforeEach(inject(function (_$location_) {
$location = _$location_;
}));
it('should return mock url', function(){
var path = $location.path();
expect(path).toBe('/somewhere'); //Assert that $location.path() returns '/somewhere'
});
I think I would simply use an angular service decorator to mock or totally replace your service for tests. Here is an example
I have never unit tested a service in a service, not yet anyways but our authertication/login stuff is coming up soon.
As you are unit testing the loginService you are only interested in the way the service interacts with the data it is given by the AuthService and not that the AuthService is working correctly. Which is what you have set up in the mock.
I think this would be my approach: (inside the parent describe)
var
loginService,
authService
AUTH_DATA
;
beforeEach(function() {
module('ql');
// I am assuming this is the global app module so both services live here? If not include this module as well
});
beforeEach(inject(function (_authService_, _loginService_) {
authService = _authService_;
loginService = _loginService_;
//Now with the spy setup you intercept the calls to the service and you choose what data to return, based on the unit test. Now your LoginService can simply resond to the data it is give from the login service
}));
it('it should do something', function () {
spyOn(authService, 'loginConfirmed').andReturn(AUTH_DATA);
loginService.confirmLogin(); //Dont know your actual API but a contrived guess
expect('something to happen in loginservice when AUTH_DATA is returned').toBe('Something else')
});

How do unit test with angular-translate

I have uses angular translate from here (http://pascalprecht.github.io/angular-translate/) and it's just work fine, but it break my controller's unit test whith Error:
Unexpected request: GET scripts/i18n/locale-en.json
I don't understant why?
I use yeoman and test with karma.
app.js:
'use strict';
(function() {
angular.module('wbApp', ['authService', 'authUserService', 'checkUserDirective', 'ui.bootstrap', 'pascalprecht.translate'])
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/login.html',
controller: 'LoginCtrl',
access: {
isFree: true
}
})
.when('/main', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
access: {
isFree: false
}
})
.otherwise({
redirectTo: '/'
});
});
})();
configTranslate.js:
'use strict';
(function() {
angular.module('wbApp')
.config(['$translateProvider',
function($translateProvider) {
$translateProvider.useStaticFilesLoader({
prefix: 'scripts/i18n/locale-',
suffix: '.json'
});
$translateProvider.preferredLanguage('en');
}]);
})();
karma.conf.js:
files = [
...
'app/bower_components/angular-translate/angular-translate.js',
'app/bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
...
];
controller test:
'use strict';
describe('Controller: LoginCtrl', function() {
// load the controller's module
beforeEach(module('wbApp'));
var LoginCtrl, scope, location, httpMock, authUser;
// Initialize the controller and a mock scope
beforeEach(inject(function($controller, $rootScope, $location, $httpBackend, AuthUser) {
authUser = AuthUser;
location = $location;
httpMock = $httpBackend;
scope = $rootScope.$new();
LoginCtrl = $controller('LoginCtrl', {
$scope: scope
});
httpMock.when('GET', 'scripts/i18n/locale-en.json').passThrough();
}));
it(...);
...
});
if i add this in test controller, product same error:
httpMock.when('GET', 'scripts/i18n/locale-en.json').respond(200);
httpMock.flush();
or
httpMock.when('GET', 'scripts/i18n/locale-en.json').passThrough();
httpMock.flush();
i find this post How do I test controllers with Angular Translate initialized in App Config? but not helped me :/
I extensively use $httpBackend in my tests and it works fine, but in this case it is ineffective. If I comment the line:
$translateProvider.preferredLanguage('en');
obviously an error, if I add on the runtime (in my controllers)
$translate.uses(local);
I end up with the same error?
So I turn to the translation configuration (configTranslate.js) or at runtime is the same result:
Unexpected request: GET scripts/i18n/locale-en.json
Here is the syntax that I tested, either in a "beforeEach(inject(function(...});"
or in a test "it('...', function() {...});"
httpMock.expectGET('scripts/i18n/locale-en.json');
httpMock.when('GET', 'scripts/i18n/locale-en.json').passThrough();
httpMock.when('GET', 'scripts/i18n/locale-en.json').respond(data);
with at end
httpMock.flush();
I also tried a $ apply
httpMock.expectGET('scripts/i18n/locale-fr.json');
scope.$apply(function(){
$translate.uses('fr');
});
httpMock.flush();
nothing happens, Still this error is driving me crazy ..
If you have any suggestion
it's a known issue, please follow the documentation here: unit testing angular
The solution
Unfortunately, this issue is caused by the design of
angular-translate. To get around these errors, all we can do is to
overwrite our module configuration in our test suite, that it doesn't
use asynchronous loader at all. When there's no asynchronous loader,
there's no XHR and therefore no error.
So how do we overwrite our module configuration at runtime for our
test suite? When instantiating an angular module, we can always apply
a inline function which is executed as configuration function. This
configuration function can be used to overwrite the modules
configuration since we have access to all providers.
Using the $provide provider, we can build a custom loader factory,
which should then be used instead of the static files loader.
beforeEach(module('myApp', function ($provide, $translateProvider) {
$provide.factory('customLoader', function () {
// loader logic goes here
});
$translateProvider.useLoader('customLoader');
}));
Please read more in the above link provided.
We took the approach of ignoring the translation loader in unit tests, rather than being forced to modify each of the spec files.
One way to do it could be by separating the loader configuration to a separate file and then exclude it in karma.
So for example you can create a file app-i18n-loader.js (all other module configurations takes place in a different file):
angular
.module('myApp')
.config(loaderConfig);
loaderConfig.$inject = ['$translateProvider', '$translatePartialLoaderProvider'];
function loaderConfig($translateProvider, $translatePartialLoaderProvider) {
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: 'assets/i18n/{part}/{lang}.json'
});
$translatePartialLoaderProvider.addPart('myApp');
}
And in your karma.conf.js exclude the file:
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
//...
'bower_components/angular-translate/angular-translate.js',
'bower_components/angular-translate-loader-partial/angular-translate-loader-partial.js',
'app/**/*.mdl.js',
'app/**/*.js'
],
exclude: [
'app/app-i18n-loader.js'
],
(Note: Answer edited to a solution that does not require grunt/gulp).
I wanted a solution,
which was not too hacky
which didn't require me to change my actual application code,
which wouldn't interfere with the ability to load additional modules
and most importantly which wouldn't require me to change every
single test.
This is what I ended up with:
// you need to load the 3rd party module first
beforeEach(module('pascalprecht.translate'));
// overwrite useStaticFilesLoader to get rid of request to translation file
beforeEach(module(function ($translateProvider) {
$translateProvider.useStaticFilesLoader = function () {
};
}));
Assuming you don't need the actual translations for your unit tests, this works great. Just put the beforeEach on a global level, preferably in it's own file inside the test folder. It will be executed before every other test then.
I encountered this problem with protractor tests. My solution was to mock translations like this:
angular.module('app')
.config(function ($translateProvider) {
$translateProvider.translations('en', {});
$translateProvider.preferredLanguage('en');
})
Now no language files are downloaded, no strings get translated and I just test against the string keys in specifications:
expect(element(by.css('#title')).getText()).toEqual('TITLE_TEXT');
Try putting to test method:
it('should ...', function() {
httpMock.when('GET', 'scripts/i18n/locale-en.json').respond({});
httpMock.expectGET('scripts/i18n/locale-en.json');
scope.resetForm(); // Action which fires a http request
httpMock.flush(); // Flush must be called after the http request
}
See examples from Angular docs
Please have a look at https://github.com/PascalPrecht/angular-translate/blob/master/test/unit/service/loader-static-files.spec.js as a reference.
In general, I would recommend using a standard translation loader for unit tests (without the hassle of http loadings) which means you can provide the labels with $translateProvider.translations(). Why? Because you do not have to test the remote loading functionality which is part of angular-translate project.
None of the solutions worked for me but I came with these solutions:
1) If you need to use scope.$apply(), or should deal with states in your test (after the $apply() the 2nd approach won't work), override your app's translations with the $translateProvider.translations() method, using a plugin to load JSON files
beforeEach(module(function ($translateProvider) {
$translateProvider.translations('en', readJSON('scripts/i18n/locale-en.json'));
}));
2) If your tested controller depends on the $translate service you can use a plugin to load JSON files and combine it with $httpBackend to load your locale file when angular-translate requests it.
beforeEach(inject(function (_$httpBackend_) {
$httpBackend = _$httpBackend_;
$httpBackend.whenGET('scripts/i18n/locale-en.json').respond(readJSON('scripts/i18n/locale-en.json'));
$httpBackend.flush();
})));
Note this should be below your beforeEach(module('myApp')); or you will get an $injector error.
I made a simple mock service for $translate
$translate=function (translation) {
return {
then: function (callback) {
var translated={};
translation.map(function (transl) {
translated[transl]=transl;
});
return callback(translated);
}
}
};
Usage example here : https://gist.github.com/dam1/5858bdcabb89effca457
I use this pattern.
ApplicationModule set regular angular-translate config.
test code load 'testModule' instead of 'applicationModule'
// application module .js
(function() {
'use strict';
angular
.module('applicationModule', [
'ngAnimate',
'ngResource',
'ui.router',
'pascalprecht.translate'
])
.config(['$stateProvider', '$urlRouterProvider', '$translateProvider', '$translatePartialLoaderProvider', config]);
function config($stateProvider, $urlRouterProvider, $translateProvider, $translatePartialLoaderProvider) {
// set routing ...
$translateProvider.useStaticFilesLoader({
prefix: 'i18n/locale-',
suffix: '.json'
});
$translateProvider.useMessageFormatInterpolation();
$translateProvider.fallbackLanguage(['en']);
$translateProvider
.registerAvailableLanguageKeys(['en', 'ko'], {
'en_US': 'en',
'ko_KR': 'ko'
})
.determinePreferredLanguage(navigator.browserLanguage);
$translateProvider.addInterpolation('$translateMessageFormatInterpolation');
$translateProvider.useSanitizeValueStrategy('escaped');
}
})();
// test.module.js
(function() {
'use strict';
angular
.module('testModule', ['applicationModule'])
.config(['$translateProvider', '$translatePartialLoaderProvider', config])
.run(['$httpBackend', run]);
function config($translateProvider, $translatePartialLoaderProvider) {
$translateProvider.useLoader('$translatePartialLoader', {
urlTemplate: 'i18n/locale-en.json'
});
$translatePartialLoaderProvider.addPart('applicationModule');
}
function run($httpBackend) {
$httpBackend.when('GET', 'i18n/locale-en.json').respond(200);
}
})();
// someDirective.spec.js
describe("a3Dashboard", function() {
beforeEach(module("testModule"))
var element, $scope;
beforeEach(inject(function($compile, $rootScope) {
$scope = $rootScope;
element = angular.element("<div>{{2 + 2}}</div>");
$compile(element)($rootScope)
}))
it('should equal 4', function() {
$scope.$digest();
expect(element.html()).toBe("4");
})
})
Late to the table with this, but I got round this by specifying that Karma simply serve the files as per this entry in karma.conf.js:
files: [
...
{pattern: 'scripts/i18n/*.json', included: false, served: true},
...
]
The 2016 answer for this is to preprocess your json into your tests and properly test translations work on your directives.
I use karma-ng-json2js-preprocessor. Follow all the steps to setup your karma.conf then in your test file, prepend the relevant file as a module, then set that information in $translateProvider.
beforeEach(module('myApp', '/l10n/english-translation.json'));
// Mock translations for this template
beforeEach(module(function($translateProvider, englishTranslation) {
$translateProvider.translations('en_us', englishTranslation);
$translateProvider.useSanitizeValueStrategy(null);
$translateProvider.preferredLanguage('en_us');
}));
Note according to the plugin, it uses your filename to generate a camelcased module name. You can play with the function inside the module's /lib but basically it remove all dashes but KEEPS underscores in a camelCase. So en_us becomes En_us.
You'll also need to tell your test that it is expecting that file as a GEt.
$httpBackend.expect('GET', '/l10n/english-translation.json').respond(200);

Testing AngularJS controllers with resource services

Background:
I'm writing unit test for angular js controllers, which utilize angular $resources wrapped in services (for maintainability purposes).
Example controller:
name = 'app.controllers.UsersIndexCtrl'
angular.module(name, [])
.controller(name, [
'$scope'
'$location'
'$dialog'
'Users'
'UserRoles'
($scope, $location, $dialog, Users, UserRoles) ->
# Get users list
$scope.users = Users.query()
# rest...
])
Example resource service:
angular.module('app.services.Users', [])
.factory 'Users', ['$rootScope', '$http', '$resource', '$location' , ($rootScope, $http, $resource, $location)->
baseUrl = '/users'
Users = $resource baseUrl + '/:userId', {userId: '#_id'}
Users.getStatus = ->
console.log 'User::getStatus()'
req = $http.get baseUrl + '/status'
req.success (res)->
$rootScope.globalUserAccountSettings = res
unless $rootScope.$$phase then $rootScope.$apply()
# other, custom methods go here...
])
Most of unit test examples in angular suggest using $httpBackend and thus mocking the $http service in controllers. To be honest, I doubt if it's a good practice since if did so I'd have to hardcode request paths in all controller tests and I want to isolate unit behaviour. $httpBackend mock is really great but only if you are using $resource in controllers directly.
A typical single test using $httpBackend would look like:
it 'should be able to add a new empty user profile', ->
$httpBackend.flush()
l = $scope.users.length
$httpBackend.expect('POST', '/users').respond _.cloneDeep mockResponseOK[0]
$scope.add()
$httpBackend.flush()
expect($scope.users.length).toEqual l + 1
What if I created a mock User resource class instance, something like:
angular.module('app.services.Users', [])
.factory 'Users', ->
class Users
$save:(cb)->
$remove:->
#query:->
#get:->
Angular DI mechanisms will override old 'app.services.Users' module with this one in a transparent way and enable me to run checks with jasmine spies.
What bothers me is the fact that I wasn't able to find a single example supporting my idea. So the question is, which one would you use and why or what am I doing wrong?
I think it makes much more sense to stub this at a service level with Jasmine spies, as you suggested. You're unit testing the controller at this point, not the service -- the exact way in which an http request is made should not be a concern for this test.
You can do something in your spec like this:
var Users = jasmine.createSpyObj('UsersStub', ['query', 'get']);
beforeEach(inject(function($provide) {
$provide.factory('Users', function(){
return Users;
});
});
And then in your relevant tests, you can stub the individual service methods to return what you expect using methods like "andCallFake" on your spy object.
The best thing you can do is make a fake resource with the methods that were suppose to be called:
var queryResponse = ['mary', 'joseph'],
Users = function() {
this.query = function() {
return queryResponse;
},
scope, HomeCtrl;
};
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
HomeCtrl = $controller('HomeCtrl', {$scope: scope, Users: new Users()});
}));
it('has users in scope', function() {
expect(scope.users).toEqual(queryResponse);
});
I'm a newbie at this stuff. I've been writing my tests using coffeescript using a dsl, but I've ran into a similar problem today. The way I solved it was by creating a jasmine spy for my resource. Then I created a promise. When the promise is resolved, it will call the 'success' function that you pass in in the controller. Then in the 'it' method, I actually resolve the promise.
I think the code would look something like this using js and jasmine, but I didn't actually have time to check
beforeEach(inject(function($rootScope, $controller, $q ) {
scope = $rootScope.$new();
queryPromise = $q.defer()
User = jasmine.createSpyObject("UsersStub", ["query"]);
User.query.andCallFake(function(success,errror){queryPromise.promise.then(success,error)});
HomeCtrl = $controller('HomeCtrl', {$scope: scope, Users: new Users()});
}));
it('has users in scope', function() {
queryPrmomise.resolve({User1: {name"joe"})
expect(scope.users).toEqual(queryResponse);
});

How to unit test Angular controller with $scope.$on?

I have a controller with an event listener in my Angular app, defined as follows.
angular.module('test').controller('TestCtrl', function($rootScope, $scope, testService) {
[...]
$scope.$on("myEvent", function(args, value) {
testService.doStuff(value);
});
});
This works perfectly in the app itself. However, when I try to unit test the functionality of the controller (using Jasmine and Karma), each test method throws the following error:
TypeError: $scope.$on is not a function in [...]/testController.js
I create the controller in my test methods as follows.
it('does stuff', inject(function($rootScope, $controller, testService) {
var scope = $rootScope.$new;
$controller('TestCtrl', {
$scope : scope
});
[...]
}));
I can get around the problem by changing my controller to use rootScope instead:
$rootScope.$on(...)
but then of course the app doesn't work anymore as expected. I can also get rid of the error by introducing the $on method in my test code:
var scope = $rootScope.$new;
scope.$on = function() {};
but mocking the listener like this kind of defeats the purpose of testing my real code.
Why doesn't the test code find the $on method of the scope? (But finds it on rootScope, still...)
There must be something fundamental that I'm missing here but I haven't been able to figure it out even after lots of googling and reading the Angular source code.
$rootScope.$new is a function. You need to invoke it ($rootScope.$new()):
it('does stuff', inject(function($rootScope, $controller, testService) {
var scope = $rootScope.$new();
$controller('TestCtrl', {
$scope : scope
});
[...]
}));
Example plunk: http://plnkr.co/edit/t1x62msmOQDkNItGzcp9?p=preview