簡體   English   中英

使用Jasmine測試從viewChild調用另一個方法的方法

[英]Test a method which calls another method from the viewChild using Jasmine

我有這個方法驗證組件,它正在調用另一個組件,它是ViewChild 我正在使用this.ViewChildComponent.someMethod(); 在我試圖測試的組件中。 我試圖使用spyOn(viewChildComponent, 'someMethod').and.returnValue(true) 但是它說this.ViewChildComponent.someMethod() is undefined 我有所有依賴項,例如提供程序上ViewChildComponent的服務。 我甚至前進了一步,並調用了viewChildComponent對其服務進行調用以決定someMethod();

任何幫助都是極好的。

如果你有例如

class TestedComponent() {
     @ViewChild('ChildComp') public variableChildComponent: ChildComp;
}

在測試spec文件中聲明子組件和測試組件:

beforeEach(() => {
  TestBed.configureTestingModule({
     declarations: [ TestedComponent, ChildComp]
  })
  fixture = TestBed.createComponent(TestedComponent);
  comp = fixture.componentInstance;
  spyOn(comp.variableChildComponent, 'someMethod').and.returnValue(true);
});

這應該工作。

@DanielDrozzel的回答可以解決你的問題,但基本上它是有缺陷的,不是一個好的做法。 我想提供一個替代方案。 在Daniel的回答中,當您使用declarations: [ TestedComponent, ChildComp] ,您在TestedComponentChildComp之間的單元測試中創建緊耦合。 如果子組件停止工作,您的測試將失敗,如果它改變行為,測試可能會失敗。

這並不總是壞事,但它有時會咬你。 最好使用官方Angular Docs https://angular.io/guide/testing#nested-component-tests中提到的Component Stubs或一個非常有用的ng-mocks庫。 上面的Angular NO_ERRORS_SCHEMA提到的第三個選項是NO_ERRORS_SCHEMA但是如果要測試是否從父級調用子組件的方法,則不能使用它。

使用ng-mocks庫你需要做的就是交換

declarations: [ TestedComponent, ChildComp]在Daniel的回答中

declarations: [ TestedComponent, MockComponent(ChildComp)]

並且可以在不創建對子組件的硬依賴性的情況下測試父組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM