单元测试AngularJS中的两个相关服务和控制器

时间:2015-12-04 12:30:44

标签: angularjs unit-testing karma-runner karma-jasmine

我有一个演示应用程序,我有一个控制器,它有一个工厂作为依赖,工厂本身依赖于另一个服务。我的代码如下:

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'];

我必须使用Jasmine 2.4作为测试框架来测试karma。我已经尝试了很多在线教程,但是当每个人都尝试做一些不同的事情时,我会感到很困有些人使用$ provide来模拟服务,有些人只是注入实际的服务/工厂并使用引用,有些人没有给出任何将参数传递给服务的例子。

有人可以告诉我如何用简单的方式进行单元测试。我已经尝试过这样的事情:

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();
})
});

1 个答案:

答案 0 :(得分:0)

我终于能够解决这个问题了。我的代码如下所示:

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();
}
}]);

测试用例看起来像这样:

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
    });

}));

//测试到这里......     });

在这里,我将服务方法模拟为jasmine spy并指定了应该使用and.callFake(function(){.....})执行的函数。已经创建了一个假工厂并且其方法已经被监视。我尝试使用jasmine.createSpy创建类似于服务的假工厂,但return { getData : getData, foo : foo }给出了错误。因此,我做到了。

任何人,如果有更好的解决方案或其他解释,请分享。