在 AngularJS 中对两个相关服务和控制器进行单元测试

Unit testing two dependent services and controller in AngularJS

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

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 来模拟服务,一些简单地注入实际的 service/factory 并使用引用,一些不给出任何向服务传递参数的示例。

谁能简单地告诉我如何进行单元测试。我已经尝试过这样做:

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

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

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 间谍,并指定了应该使用 and.callFake(function(){.....}) 执行的函数。已经创建了一个假工厂,其方法已被监视。我尝试使用 jasmine.createSpy 创建类似于服务的假工厂,但 return { getData : getData, foo : foo } 给出了错误。因此,我这样做了。

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