AngularJS controller unit test with Jasmine - angularjs

I'm making a unit test for an angular controller with Jasmine but I can't get passed the error
"TypeError: Cannot read property 'running' of undefined".
The full error is posted at the bottom.
Here's the app definition...
var myApp= myApp|| angular.module('myApp', ['ngRoute', 'ngSanitize', 'ui.bootstrap']);
myApp.run(['$http', '$rootScope', 'properties', function($http, $rootScope, properties) {
//...
//Implementation of custom dependency
properties.get().then(function(response) {
$rootScope.propertiesLoaded = true;
myApp.properties = response;
});
//...
}]);
The controller..
myApp.controller('myController', function($scope, users) {
//...
});
The test.js
describe("Test Controllers", function () {
beforeEach(function () {
angular.module("myApp");
//Injection of mocked custom dependency into the myApp.run method
myApp.run(function ($provide) {
$provide.provider('properties', function () {
this.$get = function () {
return "Mock return"
};
});
});
});
describe("myController", function () {
var scope, usrs, createMainController, mockDependency;
beforeEach(function () {
mockDependency = {
current: {
get: function () {
return "Mock return";
}
}
};
angular.module(function ($provide) {
$provide.value('users', mockDependency);
},[]);
inject(function (_$injector_, _$controller_, _$rootScope_, users) {
scope = _$rootScope_.$new();
usrs = _$injector_.get("users");
_$controller_("myController", {
$scope: scope,
users: usrs
});
createMainController = function () {
return _$controller_("myController", {
$scope: scope,
users: usrs
});
};
});
});
describe("This simple test", function () {
it("should pass no matter what", function () {
expect(true).toBe(true);
});
});
});
});
Here's the whole error message...
TypeError: Cannot read property 'running' of undefined
at isSpecRunning (file:///C:/.../angular-mocks.js:1923:73)
at window.inject.angular.mock.inject (file:///C:/.../angular-mocks.js:2087:20)
Next line points to inject function
at Object.<anonymous> (file:///C:/.../mySpec.js:37:13)
at attemptSync (file:///C:/.../jasmine.js:1510:12)
at QueueRunner.run (file:///C:/.../jasmine.js:1498:9)
at QueueRunner.execute (file:///C:/.../jasmine.js:1485:10)
at Spec.Env.queueRunnerFactory (file:///C:/.../jasmine.js:518:35)
at Spec.execute (file:///C:/.../jasmine.js:306:10)
at Object.<anonymous> (file:///C:/.../jasmine.js:1708:37)
at attemptAsync (file:///C:/.../jasmine.js:1520:12)
Here is a related reference to the error that I found which suggests it is an existing problem with Jasmine. However, in this case the problem involved Mocha, which I'm not using.
https://github.com/angular/angular.js/issues/1467

I'm not sure if this will help you, but you could give this a shot, I've had that problem. I'm not very good with AngularJS so if this doesn't work I don't know what to tell you. In your angular-mocks.js find the function isSpecRunning and change it into this:
function isSpecRunning() {
//return currentSpec && (window.mocha || currentSpec.queue.running);
return !!currentSpec;
}
I read something about Jasmine 2.0 (not sure if that's what you're on) not behaving unless you have this line.
They have fixed this issue using the above logic in newer version of angular-mocks.js (v 1.3.15).

Related

AngularJS component controller testing with Jasmine fails for service returning a promise

I've searched the internet but didn't find a solution that works for me. The situation is that I have a component with a controller. I can use Jasmine to test that the controller is created and I can also call the $onInit hook without a problem.
However, when I try to call a component function that uses a service function that returns a promise, things fail miserably. I'm using the following versions:
AngularJS v1.5.11
Jasmine v3.3.0
Karma v3.1.4
My simplified component is:
(function ()
{
"use strict";
angular
.module("app")
.component("MyComponent", {
controller: "MyController"
})
.controller("MyController", MyController);
function MyController(MyService)
{
"ngInject";
var vm = this;
vm.$onInit = $onInit;
vm.onPaginate = onPaginate;
function $onInit()
{
vm.data = [];
}
function onPaginate()
{
getData();
}
function getData()
{
MyService.getData().then(onComplete);
function onComplete(response)
{
vm.data = response.list;
}
}
}
})();
The function MyService.getData queries a REST API to retrieve some data. It will return a promise that gets resolved when the data is received. This all works in the application.
I want to test the MyController.onPaginate function and wrote the following Jasmine test spec:
describe("MyComponent: MyController", function ()
{
var $componentController, $rootScope, $q, $scope;
var componentBindings = {
};
var data = {
list: [{
"id": 23,
}],
total_count: 1
};
var mock_MyService = {
getData: function ()
{
return $q.resolve(data);
}
};
beforeEach(function ()
{
angular.mock.module("app", function ($provide)
{
$provide.value("MyService", mock_MyService);
});
angular.mock.inject(function ($injector)
{
$q = $injector.get("$q");
$componentController = $injector.get("$componentController");
$rootScope = $injector.get("$rootScope");
$scope = $rootScope.$new();
});
});
it("should retrieve data", function ()
{
var $ctrl = $componentController("MyComponent", { $scope: $scope, MyService: mock_MyService }, componentBindings);
$ctrl.$onInit();
$ctrl.onPaginate($ctrl.tableState);
$scope.$apply();
expect($ctrl.data.length).toEqual(1);
});
});
When I run this I get an error:
TypeError: e is not a function
at <Jasmine>
at b.$apply (node_modules/angular/angular.min.js:147:388)
at UserContext.<anonymous> (myComponent.spec.js:...)
at <Jasmine>
So how can I test this properly?

Mocking $mdSideNav in unit test

I have a simple enough function that closes an $mdSidenav instance in my application
function closeSideNav() {
$mdSidenav('left').close();
}
I'm now needing to unit test this, but am having trouble writing an expectation for the close() call on $mdSidenav.
I thought about using $provide in my test spec
module(function($provide) {
$provide.value('$mdSidenav', function(id) {
return {
close: jasmine.createSpy('$mdSidenav.close')
}
})
});
beforeEach(inject(function(_$controller_, _$mdSidenav_) {
$controller = _$controller_;
$mdSidenav = _$mdSidenav_;
}));
beforeEach(function() {
vm = $controller('NavbarController', {
$mdSidenav: $mdSidenav
});
});
describe('vm.closeSideNav', function() {
beforeEach(function() {
spyOn($mdSidenav, 'close');
vm.closeSideNav()
});
it('should call $mdSidenav.close()', function() {
expect($mdSidenav.close).toHaveBeenCalled();
});
});
This throws a couple of errors:
Error: close() method does not exist
Error: Expected a spy, but got undefined.
Has anyone managed to mock out $mdSidenav and offer me some guidance please?
Thanks
UPDATE
Based on the suggested answer, I have now updated my test spec to
'use strict';
describe('NavbarController', function() {
var $controller,
vm,
$mdSidenav,
sideNavCloseMock;
beforeEach(function() {
module('app.layout');
sideNavCloseMock = jasmine.createSpy();
module(function($provide) {
$provide.value('$mdSidenav', function() {
return function(sideNavId) {
return {close: sideNavCloseMock}
}
})
});
});
beforeEach(inject(function(_$controller_, _$mdSidenav_) {
$controller = _$controller_;
$mdSidenav = _$mdSidenav_;
}));
beforeEach(function() {
vm = $controller('NavbarController', {
$mdSidenav: $mdSidenav
});
});
describe('vm.closeSideNav', function() {
beforeEach(function() {
vm.closeSideNav()
});
it('should call $mdSidenav.close()', function() {
expect(sideNavCloseMock).toHaveBeenCalled();
});
});
});
And for a sanity check, my actual controller looks as follows:
(function () {
'use strict';
angular
.module('app.layout')
.controller('NavbarController', Controller);
Controller.$inject = ['$mdSidenav'];
function Controller($mdSidenav) {
var vm = this;
vm.closeSideNav = closeSideNav;
//This only affects the sideNav when its not locked into position, so only on small\medium screens
function closeSideNav() {
$mdSidenav('left').close();
}
}
})();
Unfortunately this still isn't working for me, and I end up with a different error
TypeError: undefined is not a constructor (evaluating '$mdSidenav('left').close())
close method doesn't belong to $mdSidenav. $mdSidenav is a function that returns a side nav object. That's why it complains 'close() method does not exist'.
What you can do is mock the $mdSidenav to return an object hat has mocked close method, like this: -
var sideNavCloseMock;
beforeEach(module(function($provide){
sideNavCloseMock = jasmine.createSpy();
$provide.factory('$mdSidenav', function() {
return function(sideNavId){
return {close: sideNavCloseMock};
};
});
}));
then do
it('should call $mdSidenav.close()', function() {
expect(sideNavCloseMock).toHaveBeenCalled();
});

How to write test case for JSON getting form factory in AngularJS

I am trying to write the test cass for the factory which is returing a JSON response.
But I am getting the error:
Error: [$injector:unpr] http://errors.angularjs.org/1.4.1/$injector/unpr?p0=serviceProvider%20%3C-%20service
at Error (native)
Here is my code:
(function () {
angular.module('uspDeviceService',[]).factory('getDevice', GetDevice);
GetDevice.$inject = ['$http'];
function GetDevice($http) {
getDeviceList = function() {
return $http.get("static/test-json/devices/device-list.json");
}
return {
getDeviceList: getDeviceList
}
}
}());
Code for Test case:
describe('Get Product test', function() {
beforeEach(module('uspDeviceService'));
var service, httpBackend, getDevice ;
beforeEach(function () {
angular.mock.inject(function ($injector) {
//Injecting $http dependencies
httpBackend = $injector.get('$httpBackend');
service = $injector.get('service');
getDevice = $injector.get('getDevice');
})
});
console.log('Injection Dependencies is done');
describe('get Device List', function () {
it("should return a list of devices", inject(function () {
httpBackend.expectGET("static/test-json/devices/device-list.json").respond("Response found!");
httpBackend.flush();
}))
})
});
I am new to Angular Unit testing, can anyone please help me, where I am going wrong..
Two things that jump out at me:
Your angular.module declaration is defining a module, not getting the module. I would encourage you to split that up so that it's a fair bit more clear what your intent is.
angular.module('uspDeviceService', []);
angular.module('uspDeviceService').factory('getDevice', GetDevice);
It likely works as-is, but clarity is important.
What is...service? It's not defined anywhere in your code, and Angular can't find it either, hence the error message. You may be looking to get getDevice instead. Also, name your test variable with respect to what it actually is, so you don't confuse yourself.
// defined above
var getDevice;
// while injecting
getDevice = $injector.get('getDevice');
Supposing that you have an angularjs controller myController defined in myModule. The controller do some action when the api call is success and shows a flash message when api returns success = false. The your controller code would be something like
angular.module('myModule')
.controller( 'myController', function ( $scope,flashService, Api ) {
Api.get_list().$promise.then(function(data){
if(data.success) {
$scope.data = data.response
}
else{
flashService.createFlash(data.message, "danger");
}
});
});
Now to test both success = true and success = false we
describe('myController', function(){
var $rootScope, $httpBackend, controller, flashService;
var apilink = 'http://apilink';
beforeEach(module('myModule'));
beforeEach(inject(function(_$httpBackend_,_$rootScope_, _$controller_, _flashService_) {
$rootScope = _$rootScope_;
$httpBackend = _$httpBackend_;
flashService = _flashService_;
controller = _$controller_("myController", {$scope: $rootScope});
}));
it('init $scope.data when success = true', function(){
$httpBackend.whenGET(apilink)
.respond(
{
success: true,
response: {}
});
$httpBackend.flush();
expect($rootScope.data).toBeDefined();
});
it('show flash when api request failure', function(){
spyOn(flashService, 'createFlash');
$httpBackend.whenGET(apilink)
.respond(
{
success: false
});
$httpBackend.flush();
expect(flashService.createFlash).toHaveBeenCalled();
});
});
You are always going to mock the response because here we are testing the javascript code behaviour and we are not concerned with the Api. You can see when success the data is initialized and when success is false createFlash is called.
As far as test for factory is concerned you can do
describe('Get Product test', function() {
beforeEach(module('uspDeviceService'));
var service, httpBackend, getDevice ;
beforeEach(function () {
inject(function ($injector) {
httpBackend = $injector.get('$httpBackend');
service = $injector.get('service');
getDevice = $injector.get('getDevice');
});
});
describe('get Device List', function () {
it("should return a list of devices", inject(function () {
httpBackend.expectGET("static/test-json/devices/device- list.json").respond("Response found!");
var result = getDevice.getDeviceList();
httpBackend.flush();
expect(result).toEqual('Response found!');
}));
});
});

Testing angular controller with $resource and $promise using angular-text-patterns

I am following the angular-test-patterns guide, and I get it working with my first controller test. But when I write the next test, I get the error:
TypeError: 'undefined' is not an object (evaluating '$scope.pages.$promise')
The problem then I know is the following line:
$scope.busy = $scope.pages.$promise;
But I don't know how to deal with this, especially since I am very new in test issues with JavaScript. I looking for a correct and viable way of doing this, to point me in the right direction.
The controller:
angular.module('webvisor')
.controller('page-list-controller', function($scope,Page){
$scope.pages = Page.query();
$scope.busy = $scope.pages.$promise;
});
Service:
angular.module('webvisor').
factory('Page', ['$resource', 'apiRoot', function($resource, apiRoot) {
var apiUrl = apiRoot + 'pages/:id/:action/#';
return $resource(apiUrl,
{id: '#id'},
{update: {method: 'PUT'}}
);
}]);
Test:
'use strict';
describe('Controller: page-list-controller', function () {
var ctrl, scope, rootScope, Page;
beforeEach(function () {
module('webvisor');
module(function ($provide) {
$provide.value('Page', new MockPage());
});
inject(function ($controller, _Page_) {
scope = {};
rootScope = {};
Page = _Page_;
ctrl = $controller('page-list-controller', {
$scope: scope,
$rootScope: rootScope
});
});
});
it('should exist', function () {
expect(!!ctrl).toBe(true);
});
describe('when created', function () {
// Add specs
});
});
Mock:
MockPage = function () {
'use strict';
// Methods
this.query = jasmine.createSpy('query'); // I dont know if this is correct
return this;
};
With Mox, your solution would look like this:
describe('Controller: page-list-controller', function () {
var mockedPages = []; // This can be anything
beforeEach(function () {
mox
.module('webvisor')
.mockServices('Page') // Mock the Page service instead of $httpBackend!
.setupResults(function () {
return {
Page: { query: resourceResult(mockedPages) }
};
})
.run();
createScope();
createController('page-list-controller');
});
it('should get the pages', function () {
expect(this.$scope.pages).toEqual(resourceResult(mockedPages));
});
});
As you see, Mox has abstracted away all those boilerplate injections like $rootScope and $controller. Futhermore there is support for testing resources and promises out of the box.
Improvements
I advise you not to put the resource result directly on the scope, but resolve it as a promise:
$scope.busy = true;
Pages.query().$promise
.then(function (pages) {
$scope.pages = pages;
$scope.busy = false;
});
The Mox test is just this:
expect(this.$scope.busy).toBe(true);
this.$scope.$digest(); // Resolve the promise
expect(this.$scope.pages).toBe(mockedPages);
expect(this.$scope.busy).toBe(false);
NB: You also can store the result of createScope() into a $scope var and reuse that everywhere, instead of accessing this.$scope.
After some research and many try and error cases, I answer myself with a possible solution, but I expect to find some more usable and not too repetitive soon. For now, I am satisfied with this, using $httpBackend.
Test:
'use strict';
describe('Controller: page-list-controller', function () {
var ctrl, scope, rootScope, httpBackend, url;
beforeEach(function () {
module('webvisor');
inject(function ($controller, $httpBackend, apiRoot) {
scope = {};
rootScope = {};
httpBackend = $httpBackend;
url = apiRoot + 'pages/#';
ctrl = $controller('page-list-controller', {
$scope: scope,
$rootScope: rootScope
});
});
});
it('should exist', function () {
expect(!!ctrl).toBe(true);
});
describe('when created', function () {
it('should get pages', function () {
var response = [{ 'name': 'Page1' }, { 'name': 'Page2' }];
httpBackend.expectGET(url).respond(200, response);
httpBackend.flush();
expect(scope.pages.length).toBe(2);
});
});
});
I found this solution reading this question. This work very well, and for now, satisfied me. In future, I tried somethig like those:
angular-easy-test
mox

Jasmine unit test asynchronous controller method

I'm using Jasmine to unit test an Angular controller which has a method that runs asynchronously. I was able to successfully inject dependencies into the controller but I had to change up my approach to deal with the async because my test would run before the data was loaded. I'm currently trying to spy on the mock dependency and use andCallThrough() but it's causing the error TypeError: undefined is not a function.
Here's my controller...
myApp.controller('myController', function($scope, users) {
$scope.user = {};
users.current.get().then(function(user) {
$scope.user = user;
});
});
and my test.js...
describe('myController', function () {
var scope, createController, mockUsers, deferred;
beforeEach(module("myApp"));
beforeEach(inject(function ($rootScope, $controller, $q) {
mockUsers = {
current: {
get: function () {
deferred = $q.defer();
return deferred.promise;
}
}
};
spyOn(mockUsers.current, 'get').andCallThrough();
scope = $rootScope.$new();
createController = function () {
return $controller('myController', {
$scope: scope,
users: mockUsers
});
};
}));
it('should work', function () {
var ctrl = createController();
deferred.resolve('me');
scope.$digest();
expect(mockUsers.current.get).toHaveBeenCalled();
expect(scope.user).toBe('me');
});
});
If there is a better approach to this type of testing please let me know, thank you.
Try
spyOn(mockUsers.current, 'get').and.callThrough();
Depends on the version you have used: on newer versions andCallThroungh() is inside the object and.
Here the documentation http://jasmine.github.io/2.0/introduction.html

Resources