[英]How to execute method on child component in an Angular unit test
我正在使用默認測試設置(Jasmine + Karma)運行Angular 5應用程序。
假設有一個名為Parent的組件,它有一個方法在子組件上執行方法。
parent.component.ts
@Component({
selector: 'parent',
...
export class ParentComponent implements {
@ViewChild(ChildComponent) childComponent: ChildComponent;
executeChildComponentMethod() {
this.childComponent.methodToTest();
}
}
parent.component.spec.ts
import { ParentComponent } from './parent.component'
describe('ParentComponent' () => {
let component: ParentComponent;
let fixture: ComponentFixture<ParentComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ParentComponent],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ParentComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should trigger executeChildComponentMethod', () => {
component.executeChildComponentMethod()
});
});
這導致測試拋出錯誤說,無法執行undefined的methodToTest ..這意味着未實例化子組件。
嘗試過類似實例化it塊內的子組件,將子組件注入it塊並從測試塊中的另一個fixture(用於子組件)實例化子組件但無效。
我怎樣才能讓測試工作?
將ChildComponent
添加到declarations
數組,以便它是單元測試的一部分,這意味着它將在視圖中呈現。
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ParentComponent, ChildComponent],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
注意:您可能還必須添加ChildComponent
providers
。
編輯:
替代方法
首先,作為unit testing
的一部分,您不應該測試parent
組件內child
組件的行為。 如果只想檢查child
組件方法是否被調用,那么您可以模擬child
組件並定義您在其中測試的method
。 這樣,您無需在測試期間依賴child providers
。
請參閱此處以模擬子組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.