Angular 2 测试 ng-content [英] Angular 2 test ng-content
问题描述
我想知道是否有一种方法可以在不创建宿主元素的情况下测试 ng-content
?
例如,如果我有警报组件 -
@Component({选择器:应用警报",模板:`<div><ng-content></ng-content>
`,})beforeEach(async(() => {TestBed.configureTestingModule({声明:[警报组件]}).compileComponents();}));beforeEach(() => {夹具 = TestBed.createComponent(AlertComponent);组件 = 夹具.componentInstance;});it('应该显示ng内容', () => {});
如何在不创建宿主元素包装器的情况下设置 ng-content
?
您必须创建另一个包含此测试组件的虚拟测试组件,即.app-alert
@Component({模板:`<app-alert>Hello World</app-alert>`,})类 TestHostComponent {}
使 TestHostComponent 成为您的测试平台模块的一部分
beforeEach(async(() => {TestBed.configureTestingModule({声明:[AppAlert,TestHostComponent],}).compileComponents();}));
然后实例化这个测试组件,检查它是否包含 ng-content 部分,即.你好世界"文本
it('should show ng content content', () => {const testFixture = TestBed.createComponent(TestHostComponent);const de: DebugElement = testFixture.debugElement.query(By.css('div'));const el: 元素 = de.nativeElement;expect(el.textContent).toEqual('Hello World');});
I'm wondering if there is a way to test ng-content
without creating a host element?
For example, if I have alert component -
@Component({
selector: 'app-alert',
template: `
<div>
<ng-content></ng-content>
</div>
`,
})
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AlertComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AlertComponent);
component = fixture.componentInstance;
});
it('should display the ng content', () => {
});
How can I set ng-content
without creating a host element wrapper?
You have to create another dummy test component that contains this testing component, ie. app-alert
@Component({
template: `<app-alert>Hello World</app-alert>`,
})
class TestHostComponent {}
Make TestHostComponent part of your test bed module
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppAlert, TestHostComponent],
}).compileComponents();
}));
And then instantiate this testing component, check if that contains the ng-content part, ie. "hello world" text
it('should show ng content content', () => {
const testFixture = TestBed.createComponent(TestHostComponent);
const de: DebugElement = testFixture.debugElement.query(
By.css('div')
);
const el: Element = de.nativeElement;
expect(el.textContent).toEqual('Hello World');
});
这篇关于Angular 2 测试 ng-content的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!