简体   繁体   English

如何为angularjs指令的控制器模拟服务

[英]How to mock service for angularjs directive's controller

I have a directive that i want to unit test. 我有一个要进行单元测试的指令。 This works but i need to use the service in the controller. 这有效,但我需要在控制器中使用该服务。 How do i go about this? 我该怎么办?

app.directive('myDirective', function() {
return {
    restrict: 'EA',
    scope: true,
    templateUrl: 'my-directive.html',
    controllerAs: 'md',
    link:function (scope){

    },
    controller: function($scope, $element, $stateParams,service1) {
          this.test = service1.testData;
    }
  }
});

And my unit test file so far 到目前为止,我的单元测试文件

describe("Directive : my directive", function() {
 var element, scope, controller, service1,stateParams;

 beforeEach(module("app"));
 beforeEach(module('src/templates/my-directive.html'));
 beforeEach(function() {
    service1 = {
        method : {
            name : "Test"
        }
    };
 });

 beforeEach(inject(function($compile, $rootScope ) {
   scope = $rootScope.$new();
   element = "<my-directive></my-directive>";
   element = $compile(element)(scope);
   scope.$digest();

   controller = element.controller("myDirective");

  }));

  it("should do something to the scope", function() {
     // test functions using service1
  })

});

and my service 和我的服务

app.factory('service1', function(){
      service1.testData = false;

      service1.myPromise = function (t) {
                               var deferred = $q.defer();
                               $http.get("....")
                               .success(function(result) {
                               deferred.resolve(result)
                           })
                           .error(function(error) {
                                deferred.reject(error)
                            });
                           return deferred.promise;
                        } 
});

How do i add my mocked service to my controller? 如何将模拟服务添加到控制器?

Before compiling the directive you can use the $provide service in a beforeEach block. 在编译指令之前,可以在beforeEach块中使用$ provide服务。

var service1;
beforeEach(module(function($provide) {
  service1 = {
    testData: 'Test data',
    myPromise: function() {}
  };
  $provide.value('service1', service1);
}));

If your service method returns a promise, you can spy on the method and return a promise when the method is called. 如果您的服务方法返回了一个Promise,则可以监视该方法并在调用该方法时返回一个Promise。

var deferred;
beforeEach(inject(function($q) {
  deferred = $q.defer(); 
  spyOn(service1, 'myPromise').and.returnValue(deferred.promise);
}));

So later in your specs you can reject or resolve the promise. 因此,以后您可以拒绝或兑现承诺。

deferred.resolve();
deferred.reject();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM