我正在测试类似以下的组件
@Component({
selector: 'my-component',
template: `
<my-nested-component [state]="state"></my-nested-component>
`,
encapsulation: ViewEncapsulation.Native
})
export class MyComponent {}
单元测试我的组件时,我想获得对嵌套组件MyOtherComponent
的引用。如果my-component
没有使用封装,或者它使用了模拟封装,我可以使用:
let fixture = TestBed.createComponent(MyComponent);
let nestedComponent = fixture.debugElement.query(By.directive(MyNestedComponent))
获取对组件的引用。
但是在这种情况下,query
只是查询组件的轻DOM子项(模仿querySelector
的行为),因此使用本机视图时nestedComponent
为null
封装
您应该如何获得嵌套组件的DebugElement
(以及组件实例)的引用?
答案 0 :(得分:6)
假设我们有以下组件:
@Component({
selector: 'my-nested-component',
template: `
<h1>Nested component - {{ state }}</h1>
`,
})
export class NesterComponent {
@Input() state: number;
}
@Component({
selector: 'my-app',
template: `
<my-nested-component [state]="state"></my-nested-component>
`,
encapsulation: ViewEncapsulation.Native
})
export class TestComponent {
state = 1;
}
所以我会写这样的测试:
let fixture = TestBed.createComponent(TestComponent);
let component = fixture.componentInstance;
const shadowRoot: DocumentFragment = fixture.debugElement.nativeElement.shadowRoot;
const nestedComponentNativeElement = shadowRoot.querySelector('my-nested-component');
const nestedComponentDebugElement = <DebugElement>getDebugNode(nestedComponentNativeElement);
var nestedComponentInstance: NesterComponent = nestedComponentDebugElement.componentInstance;
// here can be your code
component.state = 2;
fixture.detectChanges();
de = nestedComponentDebugElement.query(By.css('h1'));
expect(de.nativeElement.textContent).toBe('Nested component - 2');
你也可以在plunker中以 live example 的身份尝试此测试
答案 1 :(得分:1)
让我根据使用过的工具的更新版本来更新正确答案:
使用"@angular/core": "^5.2.6"
,"typescript": "~2.4.2"
和"jasmine-core": "2.5.2"
const shadowRoot: DocumentFragment = fixture.debugElement.nativeElement
const nativeElement = shadowRoot.querySelector("html-element")
const debugElement = getDebugNode(nativeElement) as DebugElement
const instance: NestedComponent = debugElement.componentInstance
expect(debugElement.query(By.css("h1")).nativeElement.textContent).toBe("ExpectedText")
答案 2 :(得分:0)
具有 Angular v6.1.8 和具有 Shadow root 的组件。 示例:
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance as AppComponent;
const shadowRoot: DocumentFragment = fixture.debugElement.nativeElement.shadowRoot;
app.active = true;
app.title = 'Title';
fixture.detectChanges();
expect(shadowRoot.querySelector('.bz-modal__header_title').textContent).toEqual('Title');