我正在尝试为 Angular 组件编写单元测试,该组件可以隐藏/显示作为组件本身的输入传递的一些内容。
预期的输入被定义为 TemplateRef。
我的组件.组件.ts
@Component({
selector: "my-component",
templateUrl: "./my-component.component.html",
styleUrls: ["./my-component.component.scss"],
exportAs: "mycomponent"
})
export class MyComponent {
private _expanded = false;
@Input()
set expanded(value: boolean) {
this._expanded = value;
}
@Input()
body: TemplateRef<any>;
@Input()
handler: TemplateRef<any>;
constructor() {}
toggleView() {
this.expanded = !this._expanded;
}
}
我的组件.component.html
<div class="wrap">
<!-- Header -->
<main #header>
<header (click)="toggleAccordion()">
<div class="handler">
<ng-container [ngTemplateOutlet]="handler">
</ng-container>
</div>
<i class="icon icon-expand" [ngClass]="{ 'icon-expand': _expanded, 'icon-collapse': !_expanded }"></i>
</header>
</main>
<!-- Body -->
<div class="body" *ngIf="_expanded">
<ng-container [ngTemplateOutlet]="body"></ng-container>
</div>
</div>
我想测试通过输入“body”传递的内容是否可见,但我不知道如何在 jasmine 中实例化带有 TemplateRef 输入的“my-component”。
Angular 文档解释了如何传递输入 https://angular.io/guide/testing#component-with-inputs-and-outputs在单元测试脚本上,但由于 TemplateRef 是一个抽象类,我无法实例化任何 TemplateRef 对象,所以我不知道如何管理它。
我的组件.组件.spec.ts
...
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyComponent]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
component.body = /* What should I put here? */;
fixture.detectChanges();
});
....