首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AngularJS测试replace设置为true的指令

AngularJS测试replace设置为true的指令
EN

Stack Overflow用户
提问于 2013-05-03 23:38:45
回答 2查看 2K关注 0票数 6

我的<custom-directive>replace:truetemplate: '<img />'。我该如何为它编写单元测试呢?我想我想测试一下它是否真的用img代替了自定义指令。

代码语言:javascript
复制
it('should be transformed to <img>', function(){
  var elm = $compile('<custom-directive></custom-directive>')(scope);
  scope.$digest();

  var t = elm.find('img'); // wrong! it replaces the element. it won't find another one inside
 //expect(elm).toBeAnImgElement ?
});

我找不到合适的匹配者。我见过的最接近的情况是检查内容(elm.html()elm.text()),但我的标记是空的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-04 14:26:39

将指令包装在div中,如下所示:

代码语言:javascript
复制
describe('Directive: custom', function () {
  beforeEach(module('App'));

  var element, $scope;

  it('should be transformed to <img>', inject(function ($rootScope, $compile) {
    $scope = $rootScope.$new();
    element = angular.element('<div><custom-directive></custom-directive></div>');
    element = $compile(element)($scope);

    expect(element.children('img').length).toBe(1);
  }));
});
票数 18
EN

Stack Overflow用户

发布于 2013-05-04 02:01:28

您可以获取实际的HTMLElement对象并检查其标记名。使用elm[0]获取实际的HTMLElement

代码语言:javascript
复制
expect(elm[0].tagName).toEqual('A');
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16362681

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档