Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 带有注入服务的单元测试角度指令_Angularjs_Unit Testing_Angularjs Directive - Fatal编程技术网

Angularjs 带有注入服务的单元测试角度指令

Angularjs 带有注入服务的单元测试角度指令,angularjs,unit-testing,angularjs-directive,Angularjs,Unit Testing,Angularjs Directive,如何对该指令进行单元测试,该指令向MyService发出$http调用?如何正确模拟或监视MyService angular.module('example') .directive('myDirective', ['MyService', function(MyService) { return { restrict: 'E', replace: true, templateUrl: 'templates/myDirec

如何对该指令进行单元测试,该指令向
MyService
发出$http调用?如何正确模拟或监视
MyService

  angular.module('example')
    .directive('myDirective', ['MyService', function(MyService) {
      return {
        restrict: 'E',
        replace: true,
        templateUrl: 'templates/myDirective.html',
        scope: {
          name: '@',
          required: '='
        },
        link: function(scope, el, attrs, billingCtrl) {
          scope.data = [];

          MyService.get()
            .then(function(res) {
              scope.data = res;
            });
        }
      };
    }]);
我的测试:

  describe('Directive: <my-directive>', function() {
    // setup code
    beforeEach(module('example'));

    var element;
    var compile;
    var scope;
    var compiledElementScope;
    var validTemplate = '<my-directive ng-model="testModel" name="test"></my-directive>';
    var MyService = { get: function() {} };
    var $q;

    function getCompiledElement(template) {
      var compiledElement;

      compiledElement = compile(template || validTemplate)(scope);
      scope.$digest();

      return compiledElement;
    }

    beforeEach(function() {
      module(function($provide) {
        $provide.value('MyService', MyService);
      });

      inject(function($compile, $rootScope, _$q_) {
        compile = $compile;
        scope = $rootScope.$new();
        $q = _$q_;
      });

    });

    describe('my directive', function() {
      var element;

      beforeEach(function() {
        element = getCompiledElement(validTemplate);
      });

      it('should make a call to MyService and update scope.data', function() {
        // how do I asset the following
        expect(scope.data).toEqual(...);
      });
    })
  });
descripe('指令:',函数(){
//设置代码
在每个(模块(“示例”)之前;
var元素;
var编译;
var范围;
var编译元素范围;
var validTemplate='';
var MyService={get:function(){};
var$q;
函数getCompiledElement(模板){
var编译元素;
compiledElement=编译(模板| |有效模板)(范围);
范围。$digest();
返回编译元素;
}
beforeach(函数(){
模块(功能($提供){
$provide.value('MyService',MyService);
});
注入(函数($compile、$rootScope、$q){
compile=$compile;
scope=$rootScope.$new();
$q=$q;
});
});
描述('我的指令',函数(){
var元素;
beforeach(函数(){
元素=getCompiledElement(有效模板);
});
它('应该调用MyService并更新scope.data',function(){
//我如何评估以下内容
expect(scope.data).toEqual(…);
});
})
});

而不是编写
var MyService={get:function(){}
在将模拟服务应用于提供者的
beforeach
中创建一个spy对象

像这样的方法应该会奏效: var-MyService

beforeEach(function() {
  MyService = jasmine.createSpyObj('MyService', ['get']);

  MyService.get = jasmine.createSpy('get').and.callFake(function () {
        return {
            then: function (callback) {
                callback(<RETURN_DATA>);
                return this;
            }
        };
    });

  module(function($provide) {
    $provide.value('MyService', MyService);
  });

  ... 

});
beforeach(函数(){
MyService=jasmine.createSpyObj('MyService',['get']);
MyService.get=jasmine.createSpy('get')。和.callFake(函数(){
返回{
然后:函数(回调){
回调();
归还这个;
}
};
});
模块(功能($提供){
$provide.value('MyService',MyService);
});
... 
});

对于
,只需返回希望保存到
范围中的模拟结果。数据

必须使用ng mock的$httpBackend服务

此服务允许您期望发出http请求并模拟响应

如果未提出请求,则测试失败

$httpBackend.when。。。这表示如果发出http请求,则按如下方式响应。。。没有期望,因此,如果没有提出请求,测试不会失败

$httpBackend.flush()表示立即发出任何挂起的请求。如果没有挂起的请求,它将失败

别忘了

afterEach(function () {
  httpBackend.verifyNoOutstandingExpectation();
  httpBackend.verifyNoOutstandingRequest();
});
最后,$httpBackend将抱怨是否动态请求HTML文件。为了避免这种情况,请在karma.conf.js中预加载所有HTML文件

    preprocessors: {
      'src/**/!(*spec)*.js': ['coverage'],
      'dest/**/*.html': ['ng-html2js']
    },
    ngHtml2JsPreprocessor: {
      stripPrefix: 'dest/',
      moduleName: 'ngHtmlFiles'
    },
    coverageReporter: {
      type: 'html',
      dir: 'coverage'
    },
    files: [
      'dest/vendor.min.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'src/**/*.js',
      'dest/**/*.html'
    ]
我知道这种配置设置很麻烦,但如果您想遵循行业惯例,则需要使其正常工作:)