Unit test $mdDialog angular material - angularjs

I called one $mdDialog inside a function. I want to unit-test $mdDialog ok and cancel cases.
The below is my controller code (app.controller.js).
(function () {
'use strict';
app.controller('AppCtrl', AppCtrl);
AppCtrl.$inject = ['$scope', '$mdDialog'];
function AppCtrl($scope, $mdDialog) {
$scope.saveEntry = function (ev) {
var confirm = $mdDialog.prompt()
.title('Save Entry')
.textContent('If you want, you can add a description to explain what you changed.')
.placeholder('Version Description')
.ariaLabel('Version Description')
.initialValue('')
.targetEvent(ev)
.ok('Save')
.cancel('Cancel');
$mdDialog.show(confirm).then(function (result) {
$scope.status = true;
}, function () {
$scope.status = false;
});
};
}
})();
The following is the spec code (app.controller.spec.js) :
describe('Unit test AppController: mdDialog', function () {
var $controller, $mdDialog;
beforeEach(function () {
module('App');
inject(function (_$controller_, _$mdDialog_) {
$controller = _$controller_;
$mdDialog = _$mdDialog_;
});
});
it(': Opened', function () {
var $scope = {};
var controller = $controller('AppCtrl', { $scope: $scope });
var $mdDialogOpened = false;
$mdDialog.show = jasmine.createSpy().and.callFake(function () {
$mdDialogOpened = true;
});
$scope.saveEntry();
$scope.$digest();
expect($mdDialog.show).toHaveBeenCalled;
expect($mdDialogOpened).toBe.true;
});
});
when I running the above code I'm getting the following error:
TypeError: Cannot read property 'then' of undefined
I referred this GitHub issue https://github.com/angular/material/issues/1482. But I'm not getting solution for my problem
Thanks in advance

The problem is that you are injecting one version of $mdDialog, and trying to test on another one.
You could try something like this:
describe('Unit test AppController: mdDialog', function () {
var ctrl, mdDialog, scope;
beforeEach(function () {
module('App');
inject(function ($rootScope, $controller, $mdDialog) {
scope = $rootScope.$new();
mdDialog = $mdDialog; //keep the reference, for later testing.
spyOn(mdDialog, 'show');
mdDialog.show.and.callFake(function () {
return {
then: function (callBack) {
callBack(true); //return the value to be assigned.
}
}
});
ctrl = $controller('AppCtrl',{$scope:scope, $mdDialog:mdDialog}); //Inject the dependency
});
});
it(': Opened', function () {
scope.saveEntry(); //exercise the method.
scope.$digest();
expect(mdDialog.show).toHaveBeenCalled();
expect(scope.status).toBe(true);
});
});
Something very similar should work.
hope this help.

Related

Method undefined in Angular JS service unit test

I am writing unit tests for my existing AngularJS app. There are just four methods in this service. I was able to getFollowUpList to work, but refresh() is not working and it is a very simple method.
The refresh method should simply set deferredGetFollowUpList = null and return true in my test.
There error I'm getting is: TypeError: Cannot read property 'then' of undefined, so my refresh method is undefined. Why is this the case? Thanks
Service
(function () {
"use strict";
angular
.module("all.patient.details")
.factory("followUpListService", ["$rootScope", "$http", "userContext", "$q", "$uibModal", "htmlBaseUrl", FollowUpListService]);
function FollowUpListService($rootScope, $http, userContext, $q, $uibModal, htmlBaseUrl) {
var deferredGetFollowUpList = null;
return {
getFollowUpList: getFollowUpList,
displayModal: displayModal,
refresh: refresh,
save: save
}
function refresh() {
deferredGetFollowUpList = null;
}
}
})();
Unit Test
describe("followUpListService", function () {
beforeEach(module("all.patient.details"));
var followUpListService = {};
var $httpBackend;
var htmlBaseUrlMock;
var returnedFollowUpListData;
var deferredGetFollowUpList;
var $rootScope;
var $q;
var $uibModal;
beforeEach(function () {
htmlBaseUrlMock = { format: function () { } };
module(function ($provide) {
$provide.value("htmlBaseUrl", htmlBaseUrlMock);
});
inject(function (_$rootScope_, _$httpBackend_, _$q_, _$uibModal_, _followUpListService_) {
$rootScope = _$rootScope_;
$httpBackend = _$httpBackend_;
$q = _$q_;
$uibModal = _$uibModal_;
followUpListService = _followUpListService_;
});
});
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it("calls refresh()", function () {
followUpListService.refresh()
.then(function (data) {
deferredGetFollowUpList = data;
});
expect(deferredGetFollowUpList).toBe(null);
});
As deferredGetFollowUpList is service level variable, Can you write your test as -
followUpListService.deferredGetFollowUpList = data; //Any Mock Data
followUpListService.refresh();
expect(followUpListService.deferredGetFollowUpList).toBe(null);

Angular $scope method testing

I'm trying to test if a $scope method has been called
my controller :
(function () {
var app = angular.module('productsController',[]);
app.controller('AddProductController', ['$scope',function ($scope) {
$scope.test = function(){
return true;
};
$scope.test();
}]);
})();
and my test :
describe("Products Controller", function () {
beforeEach(function () {
module('productsController');
});
beforeEach(function () {
var createController, scope, rootScope;
});
describe('AddProductController', function () {
beforeEach(function () {
inject(function ($controller, _$rootScope_) {
rootScope = _$rootScope_;
scope = _$rootScope_.$new();
createController = function () {
return $controller("AddProductController", {
$scope: scope,
});
};
});
});
it('should call test', function(){
spyOn(scope, 'test');
createController();
scope.$apply()
expect(scope.test).toHaveBeenCalled();
})
});
});
but I got this error:
Error: test() method does not exist
$scope.test exists any when I run the app in a browser the method is been called, but if falis whne testing, any clues?
May be there is some problem in the ordering, Could you try and check if the below works?
describe('AddProductController', function() {
var createController, scope, rootScope;
beforeEach(function() {
inject(function($controller, _$rootScope_) {
rootScope = _$rootScope_;
scope = _$rootScope_.$new();
createController = function() {
return $controller("AddProductController", {
$scope: scope,
});
};
});
});
it('should call test', function() {
createController(); // To create function test in the scope
spyOn(scope, 'test');
createController(); // To execute test after spy is added.
expect(scope.test).toHaveBeenCalled();
})
});

Why am I losing my invocation context when testing code inside of a promise (angular + jasmine)

I have simple controller where I want to test mechanics inside of a promise (in this case, I want to test that foo was called when I run bar. Here's my controller:
angular.module('myModule', [])
.controller('MyCtrl', function ($q) {
var myPromise = $q.when();
this.foo = function () {
console.log('running foo');
};
this.bar = function () {
myPromise.then(function () {
this.foo();
});
};
});
And here's my jasmine test:
describe('MyCtrl', function () {
var $controller, $scope, $q;
beforeEach(inject(function ($rootScope, _$q_, _$controller_) {
$controller = _$controller_;
$q = _$q_;
$scope = $rootScope.$new();
}));
describe('bar function', function () {
it('should call the foo function', function () {
var controller = $controller('MyCtrl', { $q: $q });
spyOn(controller, 'foo');
controller.bar();
$scope.$digest();
expect(controller.foo).toHaveBeenCalled();
});
});
});
When I run this test, I get this error:
TypeError: 'undefined' is not an object (evaluating 'this.foo')
It seems that inside the then() function block, I lose invocation context referring to the controller. When the test runs and hits this.foo(), this is undefined.
'this' doesn't contain an attribute 'foo' because the context (to the outer scope) is not bound.
You could do one of the following:
1.
this.bar = function() {
var that = this;
myPromise.then(function () {
that.foo();
});
};
2.
this.bar = function() {
function onSuccess() { this.foo(); }
myPromise.then(onSuccess.bind(this));
};

How to invoke spyOn on a scope function

I have the following jasmine spec.
describe('ViewMeetingCtrl', function () {
var $rootScope, scope, $controller , $q ;
beforeEach(angular.mock.module('MyApp'));
beforeEach(inject(function ($rootScope, $controller ) {
scope = $rootScope.$new();
createController = function() {
return $controller('ViewMeetingCtrl', {
$scope: scope,
meeting : {}
});
};
}));
it('the meeting type should be equal to an object', function () {
var controller = new createController();
//some assertion
});
});
Following is my ViewMeetingCtrl.js
(function () {
'use strict';
angular.module('MyApp').controller('ViewMeetingCtrl', ViewMeetingCtrl);
ViewMeetingCtrl.$inject = ['$scope', '$state', '$http', '$translate', 'notificationService', 'meetingService', '$modal', 'meeting', 'attachmentService'];
function ViewMeetingCtrl($scope, $state, $http, $translate, notificationService, meetingService, $modal, meeting, attachmentService) {
$scope.meeting = meeting;
$scope.cancelMeeting = cancelMeeting;
function cancelMeeting(meetingId, companyId) {
meetingService.sendCancelNotices(companyId, meetingId)
.success(function () {
$state.go('company.view');
});
}
//more code
}
})();
My question that how do i invoke the spyOn (or any other jasmine spies related method) method on the above cancelMeeting() so that i can mock the method calls , returns etc. I did the following
describe('ViewMeetingCtrl', function () {
var $rootScope, scope, $controller , $q ;
beforeEach(angular.mock.module('MyApp'));
beforeEach(inject(function ($rootScope, $controller ) {
scope = $rootScope.$new();
createController = function() {
return $controller('ViewMeetingCtrl', {
$scope: scope,
meeting : {}
});
};
}));
it('the meeting type should be equal to an object', function () {
spyOn(scope, 'cancelMeeting');//cancelMeeting is inside the scope so did like this
var controller = new createController();
});
});
but i get the following output
Firefox 37.0.0 (Windows 8.1) ViewMeetingCtrl the meeting type should be equal to an object FAILED
Error: cancelMeeting() method does not exist in C:/Users/Work/MyApp/Tests/node_mo
dules/jasmine-core/lib/jasmine-core/jasmine.js (line 1895)
is the way i am invoking spyOn is wrong or any another syntax's am i missing ?. Or do i missing something fundamental here ?
The cancelMeeting function is not added to the scope until the controller is created. So I think you just need to reverse the lines in your test code:
it('the meeting type should be equal to an object', function () {
var controller = new createController();
spyOn(scope, 'cancelMeeting');
});
Your test code looks good. I think you just have to switch the order of your assignments. First define cancelMeeting and than assign it.
function cancelMeeting(meetingId, companyId) {
meetingService.sendCancelNotices(companyId, meetingId)
.success(function () {
$state.go('company.view');
});
}
$scope.cancelMeeting = cancelMeeting;
Or just:
$scope.cancelMeeting = function(meetingId, companyId) {
meetingService.sendCancelNotices(companyId, meetingId)
.success(function () {
$state.go('company.view');
});
}

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

Resources