I am trying to test a controller. The controller uses a service which is using $http to get the data from a json file (This json file is just a mock up of response returned from server)
My problem is that when I am testing the controller, it creates the controller object and even calls the service. But it doesnt call the $http mocked response. I not sure where I am going wrong. I tried looking at few examples but all of them are using $q.
My service looks like this:
(function(){
angular.module('mymodule')
.factory('MyService', MyService);
MyService.$inject = ['$http'];
function MyService($http) {
var service = {
retrieveData : retrieveData
};
return service;
function retrieveData(containerLabel){
var myGrossData = [];
var isMatchFound = false;
var myindex = containerLabel.slice(-4);
return $http.get('app/myGrossData.json').then(function(response) {
console.log('inside http retrieveData: ');
myGrossData = response.data;
var myindexExists = false;
var mydataObject = [];
var defaultdata = [];
angular.forEach(myGrossData, function (myGrossData) {
if (myindex === myGrossData.myindex) {
mydataObject = myGrossData;
isMatchFound = true;
}
if(!isMatchFound && myGrossData.myindex === '2006')
{
mydataObject = myGrossData;
}
if(myGrossData.myindex === '2006'){
defaultdata = myGrossData;
}
});
if (isMatchFound && response.status === 200)
{
return mydataObject;
}
else if(!isMatchFound && (response.status === 200 || response.status === 201)){
return defaultdata;
}
else //all other responses for success block
{
return 'Incorrect Response status: '+response.status;
}
},
function(error){
return 'Error Response: '+error.status;
}
);
}
};
})();
The controller calling it is :
(function () {
'use strict';
angular
.module('mymodule', [])
.controller('MyCtrl', MyCtrl);
MyCtrl.$inject = ['$scope', 'MyService'];
function MyCtrl($scope, MyService) {
var vm = this;
vm.datafromsomewhere = datafromsomewhere;
vm.displayData = [];
vm.disableBarCode = false;
vm.childCount = 0;
vm.headertext="Master Container Builder";
init();
function init() {
console.log('MyCtrl has been initialized!');
console.log(vm.headertext);
}
function myfunctionCalledByUI(input) {
processData(input);
}
function processData(containerLabel){
MyService.retrieveMasterContainer(containerLabel).then(function(data){
vm.displayData = data;
});
vm.disableBarCode = true;
vm.childCount = (vm.displayData.childData === undefined) ? 0: vm.displayData.childData.length;
vm.headertext="Myindex "+vm.displayData.myindex;
if ( vm.displayData.masterDataId.match(/[a-z]/i)) {
// Validation passed
vm.displayData.masterDataId ="No Shipping Label Assigned";
}
else
console.log('else: '+vm.displayData.masterDataId);
console.log('length of childData: '+vm.childCount);
}
}
})();
and finally my spec looks like this:
var expect = chai.expect;
describe('Test Controller', function () {
var rootScope, compile; MyService = {};
var $scope, $controller;
beforeEach(module('ui.router'));
beforeEach(function() {
module('mymodule');
inject(function ($rootScope, _$compile_,_$controller_) {
rootScope = $rootScope;
compile = _$compile_;
$scope = $rootScope.$new();
MyService = jasmine.createSpyObj('MyService', [
'retrieveData'
]);
$controller = _$controller_('MyCtrl', {
$scope: $scope
});
});
});
it('controller should be initialized and data should also be initialized', function() {
expect($controller).to.not.be.undefined;
expect($controller).to.not.be.null;
expect($controller.disableBarCode).to.equal(false);
expect($controller.childCount).to.equal(0);
expect($controller.headertext).to.equal("Master Container Builder");
});
it(' should process data when containerLabel is called into myfunction', function() {
$controller.handKeyed('12001');
expect(MyService.retrieveData).to.have.been.called;
expect($controller.processData).to.have.been.called;
expect($controller.disableBarCode).to.equal(true);
expect($controller.childCount).to.equal(0);
expect($controller.headertext).to.equal("Master Container Builder");
});
});
I am using following techstack if it helps:
angular 1.5
Ionic
Karma-jasmine
The code works when I run it. My issue is that when i run the test it doesnt populate the data in my vm.displayData variable. how do I make it get some data into the service. I added in some log statements and it skips it completely.
After all the test run including unrelated tests to this one, then I see the log statements from MyService. I am not sure how to approach this.
I think what you are looking for is the $httpBackend service. It will mock the request indicating the result. So, when your service hit the url, it will return what you passed to the $httpBackend configuration.
A simple example would be:
it('should list newest by category', function(){
$httpBackend
.expectGET(url)
.respond(techPosts /*YOUR MOCKED DATA*/);
$stateParams.category = 'tech';
var controller = $controller('HomeCtrl', { PostsResource: PostsResource, $stateParams: $stateParams });
controller.listNewestPosts();
$httpBackend.flush();
expect(controller.posts).toEqual(techPosts.posts);
});
Related
I have service created which returns product details via httppost request
I have controller through which i call service __getProductService.getproductDetailsPull().then(function(response){__
and i get the data in controller
I wrote a test case for this in jasmine-karma by injecting spy
__spyOn(getProduct, 'getproductDetailsPull').and.returnValue(deferred.promise);__
**But i got errors for promises **
Error 1
Expected a spy, but got deleteCtrl({ }).
Error 2
.then is not a function
Service Code
var myapp = angular.module('abcservice');
myapp.service('getProductService',function($http,$q){
var productDetails = [];
var productResponse = null;
this.setproduct= function() {
var obj = {
adminId : 15,
productOrderID: 174824929577
};
if (this.productResponse == null) {
this.productResponse = $http.post('someurl',obj).success(function(data, status, headers,config) {
this.productResponse = mapJson(data);
}).error(function(data, status, headers,config)
{
console.log("error while fetching data from spring controller:" +error);
});
}
return this.productResponse;
};
this.getproductDetailsPull = function(productResponse) {
return this.productResponse;
};
}
Controller Code
angular
.module('getCtrl', []);
getCtrl.$inject = ['$scope', '$http', '$rootScope', 'getProductService'];
function getCtrl($scope, $http, $rootScope, getProductService) {
getProductService.getproductDetailsPull().then(function(response){
$scope.displayData = response.data.productorder;
$scope.lineItemData = response.data.OrderItem;
}
}
Jasmine Test Case
describe('getCtrl Test', function() {
var $scope = null;
var $getProduct = null;
var $rootScope = null;
var deferred,$q;
beforeEach(module('abcservice','getCtrl'));
beforeEach(inject(function (_$controller_,$rootScope,getProduct,_$q_) {
$controller = _$controller_;
$scope = $rootScope.$new();
$q = _$q_;;
deferred = _$q_.defer();
spyOn(getProduct, 'getproductDetailsPull').and.returnValue(deferred.promise);
controller = $controller('getCtrl', { $scope: $scope,$rootScope: $rootScope,getProduct:getProduct });
}));
it('Exists controller, function() {
expect(controller).toHaveBeenCalled();
});
});
You have a typo, getProduct is not the name of your service. You need to inject the service like:
beforeEach(inject(function (_$controller_,$rootScope,getProductService
The spy should be int he format spyOn(object, "methodName"), so in your case:
spyOn(getProductService, 'getproductDetailsPull')
Consider doing this for your promise:
spyOn(getProductService, 'getproductDetailsPull').and.returnValue($q.when())
Your test case is a little weird I assume your just doing that to get things working but you probably want something like:
it('Product is fetched, function() {
scope.$digest(); // if your using $q you need this (maybe move it to before call)
expect(getProductService.getproductDetailsPull).toHaveBeenCalled();
});
I have a demo application where I have a controller which has a factory as dependency and factory itself depends on another service. My code is as follows:
var app = angular.module('sampleApp', ['ui.router']);
app.service("someServ", function(){
this.sendMsg = function(name){
return "Hello " + name;
}
})
app.factory("appFactory", function ($http, someServ) {
function getData(url) {
return $http.get(url);
}
function foo(){
var text = someServ.sendMsg("Monotype");
alert(text);
}
return {
getData : getData,
foo : foo
}
})
var productsController = function ($scope, $http, appFactory) {
var pct = this;
pct.url = "http://mysafeinfo.com/api/data?list=englishmonarchs&format=json";
var jsonDataPromise = appFactory.getData(pct.url);
jsonDataPromise
.then(function (response) {
pct.jsonData = response.data;
}, function (err) {
console.log("Error is: " + error);
});
pct.profun = function(){
appFactory.foo();
}
};
app.controller("productsController", productsController);
productsController.$inject = ['$scope', '$http', 'appFactory'];
I have to test with karma using Jasmine 2.4 as testing framework. I have tried many online tutorials but getting totally confused as everyone tries to do something different. Some use $provide to mock the service, some simply inject the actual service/factory and use a reference, some do not give any example of passing arguments to services.
Can someone please tell me how to do unit testing in simple terms. I have already tried doing something like this:
describe('unit testing of service and controller', function(){
beforeEach(module('sampleApp'));
var prodCtrl, $prodScope, mockfactory, mockservice;
beforeEach(function(){
mockservice = {
sendMsg : function(name){
return name;
}
}
module(function($provide){
$provide.value("someServ", mockservice);
});
inject(function($rootScope, $controller, $http, $q, appFactory){
appFactory = appFactory;
spyOn(appFactory, 'getData');
spyOn(appFactory, 'foo');
$prodScope = $rootScope.$new();
prodCtrl = $controller('productsController', {
$scope: $prodScope, $http: $http, appFactory:appFactory
});
});
});
it('appFactory has method getData and foo', function(){
appFactory.getData();
appFactory.foo();
expect(appFactory.getData).toHaveBeenCalled();
expect(appFactory.foo).toHaveBeenCalled();
})
it('productsController gets a promise back from getData', function(){
var url = "sample url";
var myPromise = prodCtrl.getData(url);
myPromise.then(function(){console.log("Promise returned");})
})
it('foo calls service method sendMsg', function(){
prodCtrl.profun();
expect(mockservice.sendMsg).toHaveBeenCalled();
})
});
I was finally able to solve this issue. My code looks like this:
var app = angular.module('sampleApp', []);
app.service("someServ", function(){
this.sendMsg = function(name){
return "Hello " + name;
}
})
app.factory("appFactory", function ($q, someServ) {
function getData() {
var defer = $q.defer();
defer.resolve("Success message");
return defer.promise;
}
function foo(){
var text = someServ.sendMsg("Monotype");
alert(text);
}
return {
getData : getData,
foo : foo
}
})
app.controller("mainController", ['$scope', '$http','appFactory', function($scope, $http, appFactory){
var mct = this;
mct.printData = function(){
var myPromise = appFactory.getData();
myPromise
.then(function(data){
alert("Promise returned successfully. Data : " + data);
}, function(error){
alert("Something went wrong.... Error: " + error);
})
}
mct.showMsg = function(){
appFactory.foo();
}
}]);
The test case looked like this:
describe('unit testing', function(){
var jsonData = {
name: "Aosis",
id: 12345
}
beforeEach(module('sampleApp'));
beforeEach(module(function($provide){
$provide.service("someServ", function(){
//this.sendMsg = function(param){}
this.sendMsg = jasmine.createSpy('sendMsg').and.callFake(function(param){})
});
$provide.factory("appFactory", function(someServ, $q){
function getData(){
var defer = $q.defer();
defer.resolve("Success message");
return defer.promise;
}
function foo(){
var facParam = "some text";
someServ.sendMsg(facParam);
}
return {
getData : getData,
foo : foo
}
});
}));
var $scope, mainController, appFactoryMock, someServMock;
beforeEach(inject(function($rootScope, $controller, $http, $q, appFactory, someServ){
appFactoryMock = appFactory;
someServMock = someServ;
$scope = $rootScope.$new();
mainController = $controller("mainController", {
$scope : $scope,
$http : $http,
appFactory : appFactoryMock
});
}));
// Tests go here....
});
Here, I have mocked service method as jasmine spy and specified the function that should get executed usingand.callFake(function(){.....}). A fake factory has been created and its methods have been spied upon. I tried to create fake factory similar to service using jasmine.createSpy but return {
getData : getData,
foo : foo
} was giving error. Hence, I did that.
Anyone, else if has better solution or some other explanation, please share.
I have a service that i wrote for a project i am currently working on and i am trying to write a unit test for it. Below is the code for the service
angular.module('services').factory('Authorization', ['$q', 'Refs', function($q, Refs) {
function isAuthorized() {
var deferred = $q.defer();
var authData = Refs.rootRef.getAuth();
var adminRef;
if(authData.google) {
adminRef = Refs.rootRef.child('admins').child(authData.uid);
} else {
adminRef = Refs.rootRef.child('admins').child(authData.auth.uid);
}
adminRef.on('value', function(adminSnap) {
deferred.resolve(adminSnap.val());
});
return deferred.promise;
}
return {
isAuthorized: isAuthorized
};
}]);
I have written a unit test for it but anytime i run the test i get this error message ' Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.'
Below is the code for the unit test i wrote for the service:
'use strict';
describe('Authorization Service', function() {
var Refs, $q, Authorization, authData, scope, deferred;
beforeEach(angular.mock.module('Sidetime'));
beforeEach(inject(function(_Refs_, $rootScope, _$q_, _Authorization_) {
Refs = _Refs_;
$q = _$q_;
Authorization = _Authorization_;
}));
iit('return admin object', function(done) {
var result;
Authorization.isAuthorized = function() {
deferred = $q.defer();
authData = {google: 'uid:112222'};
if(authData.google) {
deferred.resolve(authData);
}
return deferred.promise;
};
Authorization.isAuthorized().then(function(result) {
console.log('result', result);
expect(result).toEqual(authData);
//done();
});
});
});
I am not sure I am writing the unit test properly. I will appreciate if someone could show be a better way of writing the unit test for this service. Thanks for your anticipated assistance.
Here is a working plunkr, with slight modifications as I don't have the code to all of your dependencies:
angular.module('services', []).factory('Authorization', ['$q', function($q) {
function isAuthorized() {
var deferred = $q.defer();
deferred.resolve({authData: {google: 'uid: 1122222'}});
return deferred.promise;
}
return {
isAuthorized: isAuthorized
};
}]);
describe('Authorization Service', function() {
var $q, Authorization, scope, deferred;
beforeEach(angular.mock.module('services'));
beforeEach(inject(function($rootScope, _$q_, _Authorization_) {
$q = _$q_;
scope = $rootScope.$new();
Authorization = _Authorization_;
Authorization.isAuthorized = function() {
deferred = $q.defer();
authData = {google: 'uid:112222'};
if(authData.google) {
deferred.resolve(authData);
}
return deferred.promise;
};
}));
it('return admin object', function(done) {
var result;
var promise = Authorization.isAuthorized();
promise.then(function(result) {
expect(result).toEqual(authData);
expect(result.google).toEqual('uid:112222e');
});
deferred.resolve(result);
scope.$digest();
});
});
(function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 250;
/**
Create the `HTMLReporter`, which Jasmine calls to provide results of each spec and each suite. The Reporter is responsible for presenting results to the user.
*/
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
/**
Delegate filtering of specs to the reporter. Allows for clicking on single suites or specs in the results to only run a subset of the suite.
*/
jasmineEnv.specFilter = function(spec) {
return htmlReporter.specFilter(spec);
};
/**
Run all of the tests when the page finishes loading - and make sure to run any previous `onload` handler
### Test Results
Scroll down to see the results of all of these specs.
*/
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
//document.querySelector('.version').innerHTML = jasmineEnv.versionString();
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
http://plnkr.co/edit/DCrr6pVzF9D4OuayCZU7?p=preview
Take a look over at spies in jasmine to get a deeper introduction
I've taken Cognitroics plunkr and modified it in the way I usually write my test. Take a look at it here http://plnkr.co/edit/W5pP82CKj7tc6IO3Wj9S?p=preview
But basically what you should do is utilizing the awesomeness of spies in jasmine.
Here's how it looks like.
describe('My aweomse test suite', function(){
beforeEach(function(){
module('Awesome');
inject(function($injector){
this.MyService = $injector.get('MyService');
this.$q = $injector.get('$q');
this.$scope = $injector.get('$rootScope').$new();
spyOn(this.MyService, 'someMethod').andCallFake(function(){
var defer = this.$q.defer();
defer.resolve();
return defer.promise;
});
});
it('should do seomthing', function(){
// given
var result;
// when
this.MyServcie.someMethod().then(function(){
result = 'as promised';
});
this.$scope.$digest();
// then
expect(result).toEqual('as promised');
});
});
});
I have following factory. I have changed init method for the sake of brevity, because all that matters is that it loads json data (similar to data in test) in teamsConfig.
var AppController = angular.module("AppController");
AppController.factory('TeamFactory', ['$http', '$q',
function($http, $q) {
var teamsConfig = {};
return{
init: function() {
$http.get('navigation/TeamsConfiguration.json').success(function(data) {
teamsConfig = data;
}).error(function(msg, code) {
deferred.reject(msg);
});
return deferred.promise;
},
getCaptainName: function(team) {
return teamsConfig[team].captainName;
}
};
My Jasmine code is as below
describe('Test TeamCaptain',function(){
beforeEach(module('AppController'));
var ctrl,scope,http,route, routeParams,location,q,svc,factory;
beforeEach(inject(function(TeamFactory,$rootScope){
scope = $rootScope.$new();
TeamFactory.teamsConfig = {
"India":
{
"captain": "Dhoni",
"batsman": "Kohli"
},
"Australia":
{
"captain": "Clarke",
"batsman": "Watson"
}
};
factory = TeamFactory;
}));
it('should get the captain of the team.',function(){
var captain= '';
var team = 'India';
captain = factory.getCaptainName(team);
expect(captain).toEqual('Dhoni');
});
}));
While running tests, I'm getting error
--TypeError: 'undefined' is not an object evaluating 'teamsConfig[team].captainName'
I have changed the code from original, it may have small errors/typos.
I'm trying to write an AngularJS library for Pusher (http://pusher.com) and have run into some problems with my understanding of the digest loop and how it works. I am writing what is essentially an Angular wrapper on top of the Pusher javascript library.
The problem I'm facing is that when a Pusher event is triggered and my app is subscribed to it, it receives the message but doesn't update the scope where the subscription was setup.
I have the following code at the moment:
angular.module('pusher-angular', [])
.provider('PusherService', function () {
var apiKey = '';
var initOptions = {};
this.setOptions = function (options) {
initOptions = options || initOptions;
return this;
};
this.setToken = function (token) {
apiKey = token || apiKey;
return this;
};
this.$get = ['$window',
function ($window) {
var pusher = new $window.Pusher(apiKey, initOptions);
return pusher;
}];
})
.factory('Pusher', ['$rootScope', '$q', 'PusherService', 'PusherEventsService',
function ($rootScope, $q, PusherService, PusherEventsService) {
var client = PusherService;
return {
subscribe: function (channelName) {
return client.subscribe(channelName);
}
}
}
]);
.controller('ItemListController', ['$scope', 'Pusher', function($scope, Pusher) {
$scope.items = [];
var channel = Pusher.subscribe('items')
channel.bind('new', function(item) {
console.log(item);
$scope.items.push(item);
})
}]);
and in another file that sets the app up:
angular.module('myApp', [
'pusher-angular'
]).
config(['PusherServiceProvider',
function(PusherServiceProvider) {
PusherServiceProvider
.setToken('API KEY')
.setOptions({});
}
]);
I've removed some of the code to make it more concise.
In the ItemListController the $scope.items variable doesn't update when a message is received from Pusher.
My question is how can I make it such that when a message is received from Pusher that it then triggers a digest such that the scope updates and the changes are reflected in the DOM?
Edit: I know that I can just wrap the subscribe callback in a $scope.$apply(), but I don't want to have to do that for every callback. Is there a way that I can integrate it with the service?
On the controller level:
Angular doesn't know about the channel.bind event, so you have to kick off the cycle yourself.
All you have to do is call $scope.$digest() after the $scope.items gets updated.
.controller('ItemListController', ['$scope', 'Pusher', function($scope, Pusher) {
$scope.items = [];
var channel = Pusher.subscribe('items')
channel.bind('new', function(item) {
console.log(item);
$scope.items.push(item);
$scope.$digest(); // <-- this should be all you need
})
Pusher Decorator Alternative:
.provider('PusherService', function () {
var apiKey = '';
var initOptions = {};
this.setOptions = function (options) {
initOptions = options || initOptions;
return this;
};
this.setToken = function (token) {
apiKey = token || apiKey;
return this;
};
this.$get = ['$window','$rootScope',
function ($window, $rootScope) {
var pusher = new $window.Pusher(apiKey, initOptions),
oldTrigger = pusher.trigger; // <-- save off the old pusher.trigger
pusher.trigger = function decoratedTrigger() {
// here we redefine the pusher.trigger to:
// 1. run the old trigger and save off the result
var result = oldTrigger.apply(pusher, arguments);
// 2. kick off the $digest cycle
$rootScope.$digest();
// 3. return the result from the the original pusher.trigger
return result;
};
return pusher;
}];
I found that I can do something like this and it works:
bind: function (eventName, callback) {
client.bind(eventName, function () {
callback.call(this, arguments[0]);
$rootScope.$apply();
});
},
channelBind: function (channelName, eventName, callback) {
var channel = client.channel(channelName);
channel.bind(eventName, function() {
callback.call(this, arguments[0]);
$rootScope.$apply();
})
},
I'm not really happy with this though, and it feels as though there must be something bigger than I'm missing that would make this better.