【问题标题】:Test directive attribute without template没有模板的测试指令属性
【发布时间】:2016-09-07 13:06:06
【问题描述】:

我正在尝试对仅限于属性的 Angular 指令运行一些单元测试。现在我只是想确定该指令是否存在。

有谁知道如何测试仅作为属性的指令?

这是指令

的基本版本
function ResetCustomer() {
  return {
    restrict: 'A',
    link: (scope, elem) => {

      elem.bind('click', function() {
        //do stuff
      });
    }
  };
}

export default {
  name: 'resetCustomer',
  fn: ResetCustomer
};

... HTML

<a class="brand" reset-customer>
   <img src="path/to/image.jpg"/>
</a>

...以及测试

describe('Unit: ResetCustomer', () => {

  let element, scope, compile;

  beforeEach(() => {
    angular.mock.module('app');
    angular.mock.inject(($compile, $rootScope) => {
      scope = $rootScope.$new();
      compile = $compile;
      element = angular.element('<a reset-customer></a>');
      compile(element)(scope);
      scope.$digest();
    });
  });

  it('should exist', () => {
    expect(element).toBeDefined();
  }); 
});

【问题讨论】:

标签: angularjs unit-testing testing jasmine karma-jasmine


【解决方案1】:

你首先需要在指令上有一个可测试的东西。

例如在回调中有它分配一个范围变量 isClicked 为真/假。

然后您可以在测试中触发 .click 并断言 isClicked 应该为真。

您甚至可以加倍努力,在触发点击之前先断言 isClicked 为假。我不记得该方法叫什么,但 90% 确定它的 .trigger('click') 或 mousedown...

【讨论】:

    猜你喜欢
    • 2017-11-22
    • 1970-01-01
    • 2021-08-11
    • 2020-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多