und*_*ned 10 javascript angular
我想知道是否有一种方法可以在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', () => {
});
Run Code Online (Sandbox Code Playgroud)
如何在ng-content不创建宿主元素包装器的情况下进行设置?
小智 9
您必须创建另一个包含此测试组件的虚拟测试组件,即。 app-alert
@Component({
template: `<app-alert>Hello World</app-alert>`,
})
class TestHostComponent {}
Run Code Online (Sandbox Code Playgroud)
使 TestHostComponent 成为您的测试平台模块的一部分
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppAlert, TestHostComponent],
}).compileComponents();
}));
Run Code Online (Sandbox Code Playgroud)
然后实例化这个测试组件,检查它是否包含 ng-content 部分,即。“你好世界”文本
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');
});
Run Code Online (Sandbox Code Playgroud)
我也想知道和你一样的事情:
看完之后:角度投影测试
我最终得到了这样的结果:
@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);
});
});
Run Code Online (Sandbox Code Playgroud)