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();})});
--
You received this message because you are subscribed to the Google Groups
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.