【发布时间】:2018-02-10 09:21:13
【问题描述】:
在使用 <ng-content> 测试具有嵌入槽的 Angular 组件时,我们没有
显式意味着检查嵌入的内容是否按预期放置在组件内。
例如:
// base-button.component.ts
@Component({
selector: 'base-button',
template: `<button [type]="type">
<ng-content></ng-content>
</button>`,
})
export class BaseButtonComponent {
@Input() type = 'button';
}
基本上,在 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');
});
我们可以对组件的每个属性和方法都这样做,但是 嵌入的内容?一种解决方法是为测试目的创建一个主机组件:
// 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> 元素
在其模板中。有没有其他方法可以做到这一点?
【问题讨论】:
标签: javascript angular unit-testing testing