転置スロットを持つ角度コンポーネントを<ng-content>
でテストしている間に、 は、トランスコードされたコンテンツが意図したとおりにコンポーネント内に配置されているかどうかを確認する明示的な手段がありません。たとえば :我々はこれを行う、specファイルにコンポーネントのインスタンスを作成する際にAngularで継承されたコンテンツをテストするには?
// base-button.component.ts
@Component({
selector: 'base-button',
template: `<button [type]="type">
<ng-content></ng-content>
</button>`,
})
export class BaseButtonComponent {
@Input() type = 'button';
}
基本的には、:
// 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');
});
私たちは、コンポーネントのすべてのプロパティとメソッドのためにこれを行うことができますが、何についてコンテンツは ですか?回避策はテスト目的のために、ホストコンポーネント作成されます:あなたが想像できるよう、
// base-button.component.spec.ts
...
@Component({
template: `<base-button>Foo bar</base-button>`
})
export class BaseButtonHostComponent {}
...
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ BaseButtonComponent, BaseButtonHostComponent ]
})
.compileComponents();
}));
it('should transclude the content correctly',() => {
const hostFixture = TestBed.createComponent(BaseButtonHostComponent);
hostFixture.detectChanges();
const button = hostFixture.nativeElement.querySelector('button');
expect(button.textContent === 'Foo bar');
});
...
をしかし、これはまた、すべてのために、おそらくトランスクルードコンテンツを持つすべてのコンポーネントについて 行われ、されるように、これはしているので、かなり不便です<ng-content>
要素 がテンプレートに含まれています。これを行う別の方法がありますか?