我想知道是否有办法在不创建主机元素的情况下测试ng-content
?
例如,如果我有警报组件 -
@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', () => {
});
如何在不创建主机元素包装的情况下设置ng-content
?
答案 0 :(得分:4)
您必须创建另一个包含该测试组件的虚拟测试组件,即。 app-alert
@Component({
template: `<app-alert>Hello World</app-alert>`,
})
class TestHostComponent {}
使TestHostComponent成为测试平台模块的一部分
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppAlert, TestHostComponent],
}).compileComponents();
}));
然后实例化此测试组件,检查其中是否包含ng-content部分。 “ hello world”文字
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');
});
答案 1 :(得分:1)
我在想和你一样的事情:
查看以下内容:Angular projection testing
我最终得到了这样的东西:
@Component({
template: '<app-alert><span>testing</span></app-alert>'
})
export class ContentProjectionTesterComponent {
}
describe('Content projection', () => {
let component: ContentProjectionTesterComponent;
let fixture: ComponentFixture<ContentProjectionTesterComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ContentProjectionTesterComponent ],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ContentProjectionTesterComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('Content projection works', async () => {
let text = 'testing';
fixture = TestBed.createComponent(ContentProjectionTesterComponent);
component = fixture.componentInstance;
let innerHtml = fixture.debugElement.query(By.css('span')).nativeElement.innerHTML;
expect(innerHtml).toContain(text);
});
});