单元测试控制器

时间:2016-09-18 19:03:50

标签: angularjs unit-testing ionic-framework karma-jasmine angular-mock

我创建了一个离子应用程序并完成但是当我开始添加测试时,我遇到了$ resources的问题,在这种情况下我有这个控制器:

  .controller('newAccountCtrl', function($scope, $window, $rootScope, API, $ionicPopup, $state) {
    $scope.newData = {};
    $scope.$on('$ionicView.enter', function() {

        $scope.newData = {};
    });
    $scope.newInfo = function() {
        API.newAccountInfo().update({ restCode: $scope.newData.restore_code }, $scope.newData, function(res, header) {
            $rootScope.popup('success', "OKAY");
            $window.location.href = '#/login';
        }, function(err) {
            if (err.data == null)
                $rootScope.popup("Error", "no connection");
            else
                $rootScope.popup('error', err.data.error);
        });
    }
})

在服务中我使用函数中的$ resources发出请求:

angular.module('starter.services', [])
.factory('API', function($rootScope, $resource, $ionicPopup, $ionicLoading, $window) { return {
          newAccountInfo: function() {
            return $resource(base + '/restoreinfo/:restCode', { restCode: '@_restCode' }, {
                update: {
                    method: 'PUT'
                }
            }, {
                stripTrailingSlashes: false
            });
        }}});

并在我的测试中使用以下代码:

describe('newAccountCtrl', function() {

var controller,
    deferredLogup, scope, $q;
beforeEach(angular.mock.module('starter'));
// TODO: Load the App Module
beforeEach(module('starter.controllers'));
beforeEach(module('starter.services'));

// TODO: Instantiate the Controller and Mocks
beforeEach(inject(function($controller, _$q_, $rootScope, _API_) {
    $q = _$q_;
    scope = $rootScope.$new();
    API = _API_;

    spyOn(API, 'newAccountInfo').and.callThrough(function(callback) {
        deferredLogup.promise.then(callback);
        return { $promise: deferredLogup.promise };
    });

    controller = $controller('newAccountCtrl', {
        '$scope': scope,
        API: API
    });

}));
it('#newAccountInfo', function() {

    scope.newInfo();

    expect(API.newAccountInfo.update).toHaveBeenCalled();

})   });

但是我收到了错误:

Expected a spy, but got undefined.

我在这里误解了,代码完美无缺

1 个答案:

答案 0 :(得分:0)

只需macke工厂直接返回资源并删除功能。