gpt4 book ai didi

angular - 如何在 Angular2 中测试包含(ng-content)?

转载 作者:太空狗 更新时间:2023-10-29 18:16:18 25 4
gpt4 key购买 nike

我有一个组件要测试如下:

import {Component, OnInit, Input} from "@angular/core";

@Component({
selector: 'column',
template: '<ng-content></ng-content>',
host: {
'[class]': '"col col-" + width'
}
})
export class ColumnComponent implements OnInit {

@Input() public width: number;

ngOnInit() {
if (!this.width || this.width > 12 || this.width < 1) {
this.width = 12;
}
}

}

我无法找到一种优雅的方式来测试 <ng-content> .检查文档但找不到好的方法。

我认为拥有一个测试包装器组件会有所帮助。但是 comp不是使用的 TestContainerComponent 所以测试失败

  @Component({
selector: 'test-container',
template: `<column width="12">Hello</column>`
})
export class TestContainerComponent {
}

fdescribe(`Column`, () => {
let comp: ColumnComponent;
let fixture: ComponentFixture<ColumnComponent>;

let testContainerComp: TestContainerComponent;
let testContainerFixture: ComponentFixture<TestContainerComponent>;
let testContainerDe: DebugElement;
let testContainerEl: HTMLElement;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ColumnComponent, TestContainerComponent]
}).compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(ColumnComponent);
testContainerFixture = TestBed.createComponent(TestContainerComponent);
comp = fixture.componentInstance;

testContainerComp = testContainerFixture.componentInstance;
testContainerDe = testContainerFixture.debugElement.query(By.css('column'));
testContainerEl = testContainerDe.nativeElement.;

});


it(`Should have a width class as 'col-...' if width attribute set`, () => {
comp.width = 6;
testContainerFixture.detectChanges();
expect(testContainerEl.classList.contains(`col-${comp.width}`)).toBeTruthy();
});

});

我想我需要一种方法来获取 ColumnComponent来自 TestContainerComponent 的组件.

最佳答案

我认为你可以在不使用包装器的情况下做到这一点,因为有一种方法可以通过调用获取宿主元素:

fixture.elementRef.nativeElement;

所以这是可能的测试:

fdescribe(`Column`, () => {
let comp: ColumnComponent;
let fixture: ComponentFixture<ColumnComponent>;

let testContainerDe: DebugElement;
let testContainerEl: HTMLElement;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ColumnComponent]
}).compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(ColumnComponent);
comp = fixture.componentInstance;
testContainerEl = fixture.elementRef.nativeElement;
});

it(`Should have a width class as 'col-...' if width attribute set`, () => {
comp.width = 6;
fixture.detectChanges();
expect(testContainerEl.classList.contains(`col-${comp.width}`)).toBeTruthy();
});
});

Plunker Example

关于angular - 如何在 Angular2 中测试包含(ng-content)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42440291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com