我想知道是否有一种方法可以在不创建宿主元素的情况下测试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?
发布于 2020-05-11 15:34:27
您必须创建另一个包含此测试组件的虚拟测试组件,即。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');
});发布于 2019-02-18 21:08:04
我和你想知道同样的事情:
看过以下内容后: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);
});
});https://stackoverflow.com/questions/43965668
复制相似问题