角度2测试错误:组件具有1< ng-content>元素,但仅提供了0个广告位 [英] Angular 2 Testing error: The component has 1 <ng-content> elements, but only 0 slots were provided

查看:77
本文介绍了角度2测试错误:组件具有1< ng-content>元素,但仅提供了0个广告位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个 Greeter 组件,它接受输入字符串和包含内容的内容.我收到此错误该组件具有1个 ng-content 元素,但仅提供了0个插槽."当我添加 ng-content 标签时.如果删除它,我的测试将被正确执行.这是我的代码和测试代码.

So I have this Greeter component that accept a input string and transcluded content. I got this error "The component has 1 ng-content elements, but only 0 slots were provided." when I add in ng-content tag. If I remove that, my test will be executed with no error. Here is my code and test code.

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));
});
}) 

推荐答案

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

The issue is that ng-content is not supported in root level components. When you instantiate the component in isolation in the unit test it becomes a root in that context.

解决方法是仅出于测试目的为您的组件创建一个简单的主机组件.

The workaround is to create a simple host component for your component just for the purpose of the test.

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

现在在单元测试中实例化GreeterHost,以便您的ng-content组件不再是根.

Now instantiate GreeterHost in the unit test instead so that your ng-content component no longer is a root.

使用这种方法,您仍然可以测试greeter,但是将通过新的主机对其进行测试.

With this approach you can still test greeter, but it will be tested via the new host.

这篇关于角度2测试错误:组件具有1&lt; ng-content&gt;元素,但仅提供了0个广告位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆