Angular 1.5单元测试组件,同时忽略子组件

Pas*_*rus 9 components unit-testing mocking angularjs

我正在尝试为Angular 1.5中的组件编写单元测试.我想对该组件及其dom节点进行单元测试.该组件包含一个非常复杂的子组件.

我的目标是在不编译子组件的情况下对外部组件进行单元测试.

由于我也想测试DOM,因此使用$ componentController进行此测试是不够的.

这是我想要实现的一个简短示例:

组件代码:

angular.module('app').component('myComponent', {
  bindings: {
    username: '<',
  },
  template: `
    <span>{{ $ctrl.username }}</span>
    <my-complex-component />
  `
  controller: function () {}
});
Run Code Online (Sandbox Code Playgroud)

我的组件的单元测试:

it('my-component should render username', function () {
  var template = '<my-component username="username"></my-component>',
    element,
    scope,
    date;

  scope = $rootScope.$new();
  scope.username = 'John';

  element = $compile(template)(scope);
  scope.$digest();

  username = element.find('span');
  expect(username.text()).to.be.equal('John');
});
Run Code Online (Sandbox Code Playgroud)

我的复杂组件不应该被实例化.它应该在模板中抵制.在单元测试中创建元素应该导致

<span>John</span>
<my-complex-component />
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

Alo*_*lon 0

有一种方法可以测试它,但最终结果将是:

<span>John</span>
<ng-transclude></ng-transclude>
Run Code Online (Sandbox Code Playgroud)

组件代码:

  angular.module('app').component('myComponent', {
  enter code herebindings: {
    username: '<',
  },
  template: `
    <span>{{ $ctrl.username }}</span>
    <ng-transclude></ng-transclude>
  `,
  transclude: true, // Added property
  controller: function () {}
});
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我删除了<my-complex-component>,然后添加了<ng-transclude>

这意味着您可以从外部添加您的信息,它将被注入到 ng-transclude 的位置。

例如,在您的主 html 中:

<my-component>
    <my-complex-component></my-complex-component>
</my-component>
Run Code Online (Sandbox Code Playgroud)

将以您一开始想要的方式出现在 DOM 中:

<span>John</span>
<my-complex-component></my-complex-component>
Run Code Online (Sandbox Code Playgroud)

之后你的测试应该可以工作。

我希望这个答案是您想要的并且对您有所帮助。

  • 我不确定更改组件的标记是否是正确的方法。它使标记不太直观。另外,如果有多个子组件怎么办? (3认同)