Accessing Angular directive controller from Protractor - angularjs

Is there a way to access a directive's controller using the .controller() method inside a Protractor test? In unit tests I can do
var el = angular.element(...);
$compile(el)(scope);
var component = el.controller('nameOfDirective');
but I can't seem to figure out how to do that in a Protractor test.
Here is the code I'm trying to test...
//registration.route.js
(function () {
'use strict';
angular.module('app.account.registration').run(appRun);
appRun.$inject = ['routerHelper'];
/* #ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return [
{
state: 'registration',
config: {
url: '/registration',
template: '<registration layout="column" flex/>',
title: 'registration'
}
}
];
}
})();
//registration.component.js
(function () {
'use strict';
angular.module('app.account.registration').component('registration', {
templateUrl: 'app/account/registration/registration.html',
controller: Controller
});
/* #ngInject */
function Controller($state, UserService, SweetAlert) {
var self = this;
this.$onInit = function () {
this.state = 'unverified';
this.processing = false;
};
this.register = function (formData) {
this.processing = true;
UserService.register(formData.email).then(function (response) {
self.state = 'verify';
self.email = response.data.email;
//response.data.token will only be returned on localhost for security reasons
self.token = response.data.token;
self.processing = false;
}).catch(function (error) {
if (error.status === 422) {
SweetAlert.error('Error!', formData.email + ' already exists. Please use a unique email.');
}
self.processing = false;
});
};
}
})();

If anyone needs the answer for this, here it is:
browser.executeScript(function () {
return window.angular.element(document.body)
.find('DIRECTIVE-TAG-NAME').controller('directiveName');
}).then(function (directiveControllerInstance) {
console.log(directiveControllerInstance);
});
For example, if your directive name is "testDirective", you would do:
browser.executeScript(function () {
return window.angular.element(document.body)
.find('test-directive').controller('testDirective');
}).then(function (directiveControllerInstance) {
console.log(directiveControllerInstance);
});

Related

How to call MVC Web API Controller after AngularJS popup completes

I have an AngularJS module with code that calls a modal popup. I also have code that calls an MVC Web API controller method. Both of these functions work independently of one another right now. What I would like to happen is after the user clicks the OK button on the modal, I want to get the value of the modal text box and send it to the API controller as a parameter. The code I have so far is below:
app.js:
(function () {
'use strict';
var app = angular.module("CRNApp", ['ui.bootstrap','trNgGrid']);
var MainController = function ($scope, $http, $log, $uibModal) {
$scope.showGrid = false;
$scope.showPolicyScreen = false;
$scope.CRNViewModel = {
policyId: 0
};
$scope.openPolicyId = function () {
$uibModal.open({
templateUrl: 'templates/popupGetPolicy.cshtml',
backdrop: false,
windowClass: 'modal',
controller: function ($scope, $uibModalInstance, $log, CRNViewModel) {
$scope.CRNViewModel = CRNViewModel;
$scope.submit = function () {
}
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
},
resolve: { CRNViewModel: function () { return $scope.CRNViewModel; } }
});//end of modal.open
}; // end of scope.open fu
$scope.policyLookup = function (policyNumber) {
$scope.loading = true;
$scope.CRNViewModel.policyId = policyNumber; //"WCZ25999"
$http.post("/api/Policy"
, $scope.CRNViewModel
, { header: { 'Content-Type': 'application/json' } })
.then(function (response) {
$scope.policy = response.data;
$scope.loading = false;
$scope.showGrid = false;
$scope.showPolicyScreen = true;
})
.catch(function (error) {
console.log(error);
$scope.loading = false;
$scope.showGrid = false;
});
};
};
app.controller("MainController", MainController);
}());
The MVC API Controller method:
// POST: api/Policy
public IHttpActionResult Post([FromBody]CRNViewModel policy)
{
CRNViewModel _crnVM = new CRNViewModel();
IConditionalRenewalNotices _crn = new ConditionalRenewalNoticesRepository();
_crnVM = _crn.GetPolicyByPolicyId(policy.PolicyId);
return Json(_crnVM);
}
Return the textbox value when you close the $uibModalInstance instance and then add a callback for the modal result:
var modal = $uibModal.open({
templateUrl: 'templates/popupGetPolicy.cshtml',
backdrop: false,
windowClass: 'modal',
controller: function($scope, $uibModalInstance, $log, CRNViewModel) {
$scope.CRNViewModel = CRNViewModel;
$scope.submit = function () {
// pass in the value you want to return
$uibModalInstance.close('WCZ25999');
}
$scope.cancel = function() {
$uibModalInstance.dismiss('cancel');
};
},
resolve: { CRNViewModel: function() { return $scope.CRNViewModel; } }
});
modal.result.then(function (value) {
$scope.policyLookup(value);
});

Yet Another Asynchronous service returns Undefined

This is my service:
(function () {
'use strict';
angular
.module('app')
.service('ClientsService', Service);
function Service($http) {
function getClients() {
$http.get('app/client/clients.json')
.then(function(res){
return res.data;
});
}
return {
getClients: getClients,
};
}
})();
If I a console log inside then I can obtain the clients from the json file.
Then I want to use the service in my component:
(function () {
'use strict';
var module = angular.module('app');
module.component("client", {
templateUrl: "app/client/client.html",
controllerAs: "model",
controller: function (ClientsService) {
var model = this;
model.clients = ClientsService.getClients();
console.log(model.clients)
}
});
})();
But the log says me: undefined.
How can I fix it?
You'll need minor refactoring for this to work.
(function () {
'use strict';
angular
.module('app')
.service('ClientsService', Service);
function Service($http) {
function getClients() {
//Notice the return here? we're returning a promise.
return $http.get('app/client/clients.json')
.then(function(res){
return res.data;
});
}
return {
getClients: getClients,
};
}
})();
(function () {
'use strict';
var module = angular.module('app');
module.component("client", {
templateUrl: "app/client/client.html",
controllerAs: "model",
controller: function (ClientsService) {
var model = this;
//getClients() now returns a promise that is resolved
//when the client list is loaded
ClientsService.getClients().then(function(clients){
model.clients = clients;
console.log(model.clients);
});
}
});
})();
It is because, the http request has not been completed. You will have data only after completion of http request. You can try following code. Also return http promise from the service.
module.component("client", {
templateUrl: "app/client/client.html",
controllerAs: "model",
controller: function (ClientsService) {
var model = this;
ClientsService.getClients().then(function(clients){
model.clients = clients;
console.log(model.clients)
})
}
});
Change Service like this:
(function () {
'use strict';
angular
.module('app')
.service('ClientsService', Service);
function Service($http) {
function getClients() {
return $http.get('app/client/clients.json')
.then(function(res){
return res.data;
});
}
return {
getClients: getClients,
};
}
})();

How to test Angular controller having a service

I am having a controller and service like below
(function () {
var mockController = function ($scope, MockService) {
$scope.message = "This is a text message";
$scope.getCities = function () {
$scope.places = [];
MockService.getCities().then(function (response) {
var places = response.data["weather-app:root"].city;
if (places) {
if (Array.isArray(places)) {
$scope.places = places;
} else {
$scope.places.push(places);
}
}
});
};
};
var mockService = function ($http) {
this.getCities = function () {
return $http.get("../rest/url", {
headers: {
'Accept': 'application/yang.data+json'
}
});
};
};
angular.module("MockApp", [])
.service("MockService", mockService)
.controller("MockController", mockController);
}())
I created a mock service like below for mocking the service for unit testing.
(function () {
angular.module('mock.service', [])
.service('MockService', function ($q) {
var mockService = {};
mockService.getCities = function () {
var mydata = {
"weather-app:root": {
"city": [
{
"city-name": "Chennai"
, "country-name": "India"
}
, {
"city-name": "Mangalore"
, "country-name": "India"
}
]
}
}
return $q.when(mydata);
};
return mockService;
});
}());
My test case is like
describe("MockController", function () {
var $scope;
beforeEach(function () {
module("MockApp");
beforeEach(module('mock.service'));
inject(function (_$controller_, _$rootScope_, _MockService_) {
$scope = _$rootScope_.$new();
controller = _$controller_("MockController", {
$scope: $scope
, MockService: _MockService_
});
});
});
describe("Test", function () {
it("Should be Bangalore", function () {
$scope.getCities();
console.log($scope.places);
});
});
});
the problem is that the then method in controller is not getting called. How can I resolve the issue ?
Three things to fix...
Don't nest the beforeEach calls. You can init multiple modules with module.
beforeEach(function() {
module('MockApp', 'mock.service');
// and so on
Your mock data does not quite match what you'd see from an $http based promise response
return $q.when({data: mydata});
In order to process promises, you need to trigger a digest cycle
it("Should be Bangalore", function() {
$scope.getCities();
$scope.$apply();
console.log($scope.places);
});

angular testing with sinon, mocha, chai

I want test my angular app with mocha,sinon and chai.
Especially I interest in submit function. How to create mock or stub for LoginResoure to test this function.
Thanks!
(function () {
'use strict';
class LoginController {
constructor($state,LoginResource) {
this.resource = LoginResource;
this.$state = $state;
this.credentials = {};
}
submit() {
let promise = this.resource.login(this.credentials);
promise.then(()=>{
changeState()
}
}
changeState() {
this.$state.go('home');
}
}
angular.module('app.login').controller('LoginController', LoginController);
})();
(function () {
'use strict';
class LoginResource {
constructor($resource, API_LOGIN) {
this.$resource = $resource(API_LOGIN,{'#id':id})
}
login(data) {
return this.$resource.save(data).$promise;
}
}
angular.module('app.login').service('LoginResource', LoginResource);
})();
EDIT:
Previously I do it with jasmine in next way:
let deferred = $q.defer();
deferred.resolve('Remote call result');
mockPeopleResource = {
createPerson: jasmine.createSpy('createPerson').and.returnValue(deferred.promise)
};
or if I want mock #resource
mockThen = jasmine.createSpy();
mockGetPeoplePromise = {then: mockThen};
mockUpdate = jasmine.createSpy().and.returnValue({$promise: mockPromise});
mockSave = jasmine.createSpy().and.returnValue({$promise: mockPromise});
mockGetPeopleQuery = jasmine.createSpy().and.returnValue({$promise: mockGetPeoplePromise});
mockResource = jasmine.createSpy().and.returnValue({
get: mockGet,
update: mockUpdate,
save: mockSave,
query: mockGetPeopleQuery
});
If you want to mock a service, you can create a test module when you set the mocked value:
beforeEach(function() {
angular.module('test', []).factory('LoginResource', function($q) {
return {
/* You can mock an easy login function that succeed when
data >= 0 and fails when data < 0 */
login: function(data) {
return $q(function(resolve, reject) {
if (data >= 0) return resolve();
reject();
});
}
};
});
module('app.login', 'test');
});

Need help completing unit test for angular $modal

I am trying to get the "make sure modalInstance.result.then is executed" test in my code to pass. Right now it says Expected [ undefined, 'http://www.link1.com', 'http://www.link2.com', 'http://www.link3.com' ] to contain 'http://www.pressboardmedia.com' I believe this has something to do with the promise needing to be mocked so it passes along the campaignLink but I am unsure if this is the problem and cannot seem to get it to work regardless. please let know if you have any ideas.
Thanks!
Controller File
angular.module('pb.campaignLinks.controllers')
.controller('CampaignLinksController', ['$scope', '$timeout', '$modal', '$stateParams', 'global', 'campaignLinkService', function ($scope, $timeout, $modal, $stateParams, global, campaignLinkService) {
$scope.init = function (currentView) {
$scope.partialViews = {
campaignLinkList: "/app/campaignLinks/views/_list.html",
};
$scope.currentView = currentView;
$scope.getCampaignLinks(currentView, 10);
};
$scope.getCampaignLinks = function (currentView, length, continuationToken) {
// When loading list items, display loading image
if ($scope.campaignLinks) $scope.campaignLinks.loading = true;
var promiseObj = null;
if (currentView.campaignId && currentView.campaignId !== 0 && !currentView.buyRequestId) {
promiseObj = campaignLinkService.getCampaignLinks(global.activeOrganizationId, currentView.campaignId, length, continuationToken)
} else if (currentView.campaignId && currentView.buyRequestId && currentView.campaignId !== 0 && currentView.buyRequestId !== '') {
promiseObj = campaignLinkService.getCampaignBuyRequestLinks(global.activeOrganizationId, currentView.campaignId, currentView.buyRequestId, length, continuationToken);
} else if (currentView.webSiteId && currentView.buyRequestId && currentView.webSiteId !== 0 && currentView.buyRequestId !== '') {
promiseObj = campaignLinkService.getWebSiteBuyRequestLinks(global.activeOrganizationId, currentView.webSiteId, currentView.buyRequestId, length, continuationToken);
}
if (promiseObj) {
promiseObj.then(function (data) {
// If there are already some campaign links being displayed, add newly loaded list to the end
if ($scope.campaignLinks) {
$scope.campaignLinks.continuationToken = data.continuationToken;
$scope.campaignLinks.total += data.total;
$.each(data.items, function (index) {
$scope.campaignLinks.items.push(data.items[index]);
});
} else {
// Otherwise add loaded list to scope
$scope.campaignLinks = data;
}
// When done loading, hide loading image
$scope.campaignLinks.loading = false;
});
}
};
$scope.openAddCampaignLink = function (campaignId) {
var modalOptions = {
templateUrl: '/app/campaignLinks/views/_add.html',
controller: 'AddCampaignLinksModalController',
resolve: {
campaignId: function () {
return campaignId;
}
}
};
var modalInstance = $modal.open(modalOptions);
modalInstance.result.then(function (campaignLink) {
// Add new item to list, otherwise wait for it to be loaded manually.
$scope.campaignLinks.items.unshift(campaignLink);
$scope.campaignLinks.total += 1;
}, function () {
console.log('Modal dismissed at: ' + new Date());
});
};
$scope.openRemoveCampaignLink = function (campaignId, campaignLink, index) {
var modalOptions = {
templateUrl: '/app/campaignLinks/views/_delete.html',
controller: 'RemoveCampaignLinksModalController',
resolve: {
campaignId: function () {
return campaignId;
},
campaignLink: function () {
return campaignLink;
}
}
};
var modalInstance = $modal.open(modalOptions);
modalInstance.result.then(function () {
// Splice the deleted item from the list without reloading all
$scope.campaignLinks.items.splice(index, 1);
$scope.campaignLinks.total -= 1;
}, function () {
console.log('Modal dismissed at: ' + new Date());
});
};
// Once everything is loaded, initialize controller
// init();
}]);
Test file:
describe('CampaignLinksController', function () {
//make module avalible to tests
beforeEach(module('pb.campaignLinks.controllers'));
beforeEach(module('ui.router'));
beforeEach(module('ui.bootstrap'));
var $controller;
var mockPromiseObj;
var length = 200;
var mockModal = {};
var mockCampaignLinks = {
total: 3,
items: ['http://www.link1.com', 'http://www.link2.com', 'http://www.link3.com']
};
var mockCurrentView = {};
var mockGlobal = { activeOrganizationId: 54 };
var continuationToken = {
nextRowKey: 'fdsf2',
nextPartitionKey: '5432gee'
};
var campaignDetails = {
campaignId: 453,
campaignLink: 'http://www.pressboardmedia.com',
index: 1
};
var mockCampaignLinkService = {
//move campaignDetails here
campaignLinks: {
total: 3,
//length here
items: ['http://www.link1.com', 'http://www.link2.com', 'http://www.link3.com']
},
//all but delete must return a promiseObj
getCampaignLinks: jasmine.createSpy('mockCampaignLinkService.getCampaignLinks').and.returnValue(mockPromiseObj),
getCampaignBuyRequestLinks: jasmine.createSpy('mockCampaignLinkService.getCampaignBuyRequestLinks').and.returnValue(mockPromiseObj),
getWebSiteBuyRequestLinks: jasmine.createSpy('mockCampaignLinkService.getWebSiteBuyRequestLinks').and.returnValue(mockPromiseObj),
deleteCampaignLink: jasmine.createSpy('mockCampaignLinkService.deleteCampaignLinks')
};
beforeEach(inject(function (_$controller_) {
$controller = _$controller_;
}));
beforeEach(inject(function ($rootScope) {
controller = $controller('CampaignLinksController',
{
$scope: scope,
$modal: mockModal,
//$stateParams: mockStateParams,
global: mockGlobal,
campaignLinks: mockCampaignLinks,
campaignLinkService: mockCampaignLinkService,
currentVeiw: mockCurrentView,
//promiseObj: mockPromiseObj
});
}));
describe('openAddCampaignLink()', function () {
var actualOptions;
var modalOptions = {
templateUrl: '/app/campaignLinks/views/_add.html',
controller: 'AddCampaignLinksModalController',
resolve: {
campaignId: jasmine.any(Function)
}
};
beforeEach(inject(function ($q) {
mockModal.open = function (options) {
actualOptions = options;
var defer = $q.defer();
defer.resolve();
return { result: defer.promise };
}
}));
it("make sure modalInstance.result.then is executed", function () {
scope.campaignLinks = mockCampaignLinkService.campaignLinks;
scope.openAddCampaignLink(campaignDetails.campaignId, campaignDetails.campaignLink, campaignDetails.index);
scope.$digest();
expect(scope.campaignLinks.total).toEqual(4);
expect(scope.campaignLinks.items).toContain(campaignDetails.campaignLink);
});
});
I think your problem is that the argument "campaignLink" that is supplied to your modalInstance.result.then function will always be undefined when you test this. The code that calls the modal close should be tested that it is supplying the campaignLink correctly. You only want to test that the proper code gets executed when the modal is closed. We do that by supplying a function that can be tested on it's own to the modalInstance.result.then call instead of doing an inline function so it can be tested easier.
Here's an example:
Here's the code that opens the modal:
$scope.editGradeClick = function () {
var modalInstance = $modal.open({
templateUrl: templateSrv.templateUrl('/Templates/App/Courses/CourseLessonGradeModal.html'),
controller: courseLessonGradeModalBootstrap,
backdrop: 'static',
keyboard: false,
resolve: {
data: $scope.editGradeModalResolve
}
});
modalInstance.result.then(
null,
$scope.editGradeModalDismissCallback
);
};
Notice how we supply a function $scope.editGradeModalDismissCallback instead of writting an inline function there for a modal dismiss. This allows us to test that logic in it's own test.
Now here is the test. We only care that the above function was called since we will be testing the specific function in it's own test. That happens at the last line in the test.
var $controllerConstructor, $scope, $q;
beforeEach(function () {
module('appModule');
inject(function ($controller, $rootScope, _$q_) {
$controllerConstructor = $controller;
$scope = $rootScope.$new();
$q = _$q_;
});
});
it('should execute $scope.editGradeModalDismissCallback when modal is dismissed', inject(function (templateSrv) {
var $modal = {};
$modal.open = function () {
var queryPromise = $q.defer();
queryPromise.reject();
return { result: queryPromise.promise };
};
$controllerConstructor('CourseLessonGradeListCtrl', { $scope: $scope, $modal: $modal, templateSrv: templateSrv});
spyOn($modal, "open").andCallThrough();
spyOn($scope, "editGradeModalDismissCallback");
$scope.editGradeClick();
$scope.$root.$digest();
expect($scope.editGradeModalDismissCallback).toHaveBeenCalled();
}));
I hope this helps you. In this example we are rejecting the promise because we are testing the modal dismiss not close, fyi...

Resources