如何嘲笑服务angularjs指令的控制器 [英] How to mock service for angularjs directive's controller

查看:131
本文介绍了如何嘲笑服务angularjs指令的控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我想要的单元测试指令。这工作,但我需要在控制器中使用该服务。我怎么去呢?

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

});

和我的服务

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?

推荐答案

编译指令可以使用​​的 $在 beforeEach 块提供服务。

Before compiling the directive you can use the $provide service in a beforeEach block.

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.

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

这篇关于如何嘲笑服务angularjs指令的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆