角度单元测试控制器与服务

时间:2016-05-25 10:46:25

标签: angularjs unit-testing

我试图使用karma和jasmine为依赖于服务的Angular控制器编写单元测试

storesController.js

(function () {
var app = angular.module('storesController', ['storesService']);

app.controller('StoresListController', function ($scope, StoresService) {


    $scope.getStores = function () {
        StoresService.getStores().then(function (data) {
            $scope.stores = data.data;
        });
    };
    $scope.getStores();

    $scope.deleteStore = function (id) {
        StoresService.deleteStore(id).then(function () {
            $scope.getStores();
        });

    };
});

storesService.js

(function () {
var app = angular.module('storesService', []);

app.factory('StoresService', ['$http', function ($http) {

        var stores = [];

        stores.getStores = function () {
           return $http.get(/api/getStores');
        };            
        stores.deleteStore = function (storeID) {
            return $http.delete(/api/deleteStore/'+storeID);
        };
        return stores;

    }]);
})();

测试, controllers.spec.js

describe('StoresController', function () {
    beforeEach(module('storesController'));

    var scope;
    var storesServiceMock;
    var controller;

    beforeEach(inject(function ($controller, $rootScope) {

        storesServiceMock = {
            getStores: function() {
            },
            deleteStores: function() {
            }
       };
       spyOn(storesServiceMock, 'getStores').and.returnValue({name : 'TestName', country : 'TestCountry'}) 

        scope = $rootScope.$new();
        controller = $controller('StoresListController', {
           $scope: scope, StoresService: storesServiceMock
       });
    }));

    it('scope.stores should be defined', function () {
          expect(scope.stores).toBeDefined;
    });
});

我正在

TypeError: StoresService.getStores(...).then is not a function at n.$scope.getStores 

我也试过宽度httpBackend,但是我无法让它发挥作用,任何关于我做错的线索?

1 个答案:

答案 0 :(得分:1)

请间谍回复承诺。

使用ES2015:

spyOn(storesServiceMock, 'getStores').and.returnValue(Promise.resolve({name : 'TestName', country : 'TestCountry'}));

使用$ q:

spyOn(storesServiceMock, 'getStores').and.callFake(function() {
    var deferred = $q.defer();
    deferred.resolve({name : 'TestName', country : 'TestCountry'}));
    return deferred.promise;
});
相关问题