在测试具有嵌入槽的 Angular 组件时<ng-content>,我们没有明确的方法来检查嵌入的内容是否按预期放置在组件内。例如:
// base-button.component.ts
@Component({
selector: 'base-button',
template: `<button [type]="type">
<ng-content></ng-content>
</button>`,
})
export class BaseButtonComponent {
@Input() type = 'button';
}
Run Code Online (Sandbox Code Playgroud)
基本上,在 spec 文件中创建组件实例时,我们这样做:
// base-button.component.spec.ts
it('should reflect the `type` property into the "type" attribute of the button', () => {
const fixture = TestBed.createComponent(BaseButtonComponent);
fixture.detectChanges();
const { componentInstance, nativeElement } = fixture;
componentInstance.type = 'reset';
const button = nativeElement.querySelector('button');
expect(button.type === 'reset');
});
Run Code Online (Sandbox Code Playgroud)
我们可以对组件的每个属性和方法都这样做,但是嵌入的内容呢?一种解决方法是创建一个用于测试目的的主机组件:
// base-button.component.spec.ts
...
@Component({
template: `<base-button>Foo bar</base-button>`
})
export class BaseButtonHostComponent …Run Code Online (Sandbox Code Playgroud)