Angular指令上的Karma测试返回意外请求

Karma test on Angular directive returns unexpected request

本文关键字:返回 意外 请求 测试 Karma 指令 Angular      更新时间:2023-09-26

我有一个简单的指令:

使用严格的;

angular
  .module('app')
  .directive('ngEmailMask', ngEmailMask);
function ngEmailMask() {
  var directive = {
    replace: true,
    restrict: 'EA',
    scope: {
      user: '@',
      host: '@'
    },
    template: '<a href="mailto:{{user}}@{{host}}">{{user}}@{{host}}</a>'
  };
  return directive;
}

我正在写一个Karma单元测试来检查指令输出正确的HTML。到目前为止,我得到了这个:

describe('ngEmailMask', function() {
  // Bindable members
  var $compile,
      $rootScope;
  // Load module
  beforeEach(angular.mock.module('app'));
  // Bind injected references to local variables
  beforeEach(inject(function(_$compile_, _$rootScope_) {
    $compile = _$compile_;
    $rootScope = _$rootScope_;
  }));
  // Verify service returns
  it('Replaces the tag with the correct HTML', function() {
    // Compile element
    var element = $compile('<ng-email-mask data-user="test" data-host="gmail.com"></ng-email-mask>')($rootScope);
    // Evaluate scope
    $rootScope.$digest();
    console.log(element.html());
  });
});

我遵循了Angular网站上的例子,但是上面的例子返回了一个错误:

Error: Unexpected request: GET /app/home/home.html

该路径与指令无关,可能会改变(这一切都与我使用的UI路由器中的状态和路由有关)。那么我如何测试这个指令而不看到这些关于不同文件的错误呢?

您必须在jasmine测试中预期所有xhr调用(甚至模板)。最简单的方法是在运行测试之前将所有模板添加到templateCache中。

参见:用templateUrl单元测试AngularJS指令