测试依赖于另一个指令Angularjs的指令

Testing a directive that depends on another directive - Angularjs

本文关键字:指令 Angularjs 另一个 依赖于 测试      更新时间:2024-05-13

我有一个包含另一个指令的指令。这是指令:

<div class="chat-container">
 <h5 class="chat-header">
  <span class="patient-name-container">{{encounter.patient.firstName }} {{encounter.patient.lastName}}</span></h5>
  <div ng-show="showMessages">
    <div  messages-container messages="encounter.comments"></div>
  </div>
</div>

这是我的测试:

  var element;
  beforeEach(module('app/views/chat.container.html'));
  beforeEach(inject(function($templateCache, $compile, $rootScope) {
    var chatTemplate = $templateCache.get('app/views/chat.container.html');
    $templateCache.put('views/chat.container.html', chatTemplate);
    var directive = angular.element('<div chat-container max-chat-count="800" class="pull-left"></div>');
    element = $compile(directive)($rootScope);
    $rootScope.$digest();
  }));
  it('the remaining count to be 800', function() {
    expect(element.find('#counter').text()).toBe('800');
  });
});

我的错误是Error: Unexpected request: GET views/messages.container.html。它正在寻找html来创建messages-container指令,但找不到。我已经尝试在第一个指令之后添加另一个类似的指令:

var messagesTemplate = $templateCache.get('app/views/messages.container.html');
$templateCache.put('views/messages.container.html', messagesTemplate);

但我还是犯了同样的错误,所以我有两个问题。第一-我该如何测试?第二,我现在创建的测试依赖于另一个指令,正确的处理方法是什么?

问题是我在尝试访问module函数之前没有添加该模板。以下是修复该问题的代码:

  var element, scope;
  beforeEach(module('app/views/chat.container.html'));
* beforeEach(module('app/views/messages.container.html'));
  beforeEach(inject(function($templateCache, $compile, $rootScope) {
    var chatTemplate = $templateCache.get('app/views/chat.container.html');
    $templateCache.put('views/chat.container.html', chatTemplate);
    var messagesTemplate = $templateCache.get('app/views/messages.container.html');
    $templateCache.put('views/messages.container.html', messagesTemplate);
    var directive = angular.element('<div chat-container max-chat-count="800" class="pull-left"></div>');
    element = $compile(directive)($rootScope);
    $rootScope.$digest();
    scope = $rootScope;
  }));

我以前没有和*的线路。现在一切都很顺利。