Angular 2测试错误:组件有1个<ng-content>元素,但只提供了0个插槽

时间:2016-04-07 01:12:48

标签: angular

所以我有 Greeter 组件接受输入字符串和转换内容。我收到此错误“该组件有1个 ng-content 元素,但只提供了0个插槽。”当我添加 ng-content 标签时。如果我删除它,我的测试将执行没有错误。这是我的代码和测试代码。

import { Component, OnInit, Input } from 'angular2/core';

@Component({
  selector: 'greeter',
  template: `
    <h1>Hello {{name}}!</h1>
    <ng-content></ng-content>  
`
})
export class Greeter {
  @Input() name: string;
}

这是我的测试代码: -

import {TestComponentBuilder, ComponentFixture, beforeEachProviders,  beforeEach, inject, describe,
expect, it, injectAsync, setBaseTestProviders } from 'angular2/testing';
import {TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS} from 'angular2/platform/testing/browser'

import {Greeter} from './noob.component';

describe('Noob: component', () => {
let tcb: TestComponentBuilder;
setBaseTestProviders(TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS);

beforeEachProviders(() => [
    TestComponentBuilder,
    Greeter
]);

beforeEach(<any>inject([TestComponentBuilder], (_tcb: TestComponentBuilder) => {
    tcb = _tcb;
}));

//specs
it('should render `John Doe!`', (done: any) => {
    tcb.createAsync(Greeter).then((fixture: ComponentFixture) => {
        let greeter = fixture.componentInstance,
            element = fixture.nativeElement;
        greeter.name = 'John Doe';
        fixture.detectChanges(); //trigger change detection
        expect(element.querySelector('h1').innerText).toBe('Hello John Doe!');
        done();
    })
        .catch((e: any) => done.fail(e));
});
}) 

1 个答案:

答案 0 :(得分:2)

问题是根级别组件不支持ng-content。当您在单元测试中单独实例化组件时,它将成为该上下文中的根。

解决方法是为组件创建一个简单的主机组件,仅用于测试。

@Component({
  directives:[Greeter],
  template:'<greeter></greeter>'
})
class GreeterHost{
}

现在在单元测试中实例化GreeterHost,以便你的ng-content组件不再是root。

使用这种方法,您仍然可以测试接收器,但它将通过新主机进行测试。