[英]Access DebugElement of nested component when using native view encapsulation
我正在測試如下組件
@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
(以及組件實例)的引用?
假設我們有以下組件:
@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
讓我根據更新版本的舊工具更新正確答案:
以下是它對我有用的方法,使用"@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")
使用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');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.