1

我正在嘗試測試組件中的Subject變更,但覆蓋範圍永遠不會進入訂閱功能。Angular Unit Test Observable/Subject with Karma

標題欄-search.component.ts

export class TitlebarSearch implements OnInit { 

    @ViewChild('titleSearchInput') titleSearchInputEl: any; 
    @Input() inputValue: string; 
    @Output() searchText = new EventEmitter<string>(); 
    searchChange: Subject<string> = new Subject<string>(); 


    constructor(private renderer: Renderer) { 

    }  

    /** 
    * Waits a time before send the text to search 
    * 
    * @protected 
    * @memberof TitlebarSearch  
    * 
    */ 
    protected prepareSearchInput() { 
     this.searchChange.debounceTime(500).subscribe(value => { 
      this.searchText.emit(value); 
     }); 
    } 

    /** 
    * Send the text to the searchChange Observable 
    * 
    * @param {string} text 
    * @memberof TitlebarSearch 
    */ 
    public doSubmit(text:string){ 
     this.searchChange.next(text);   
    }  

} 

標題欄-search.component.spec.ts

describe('Titlebar Search tests',() => { 
    let fixture; 
    let titlebarComponent; 

    beforeEach(async(() => { 
     //Creates a UserService using a mock class 
     TestBed.configureTestingModule({ 
      declarations: [TitlebarSearch], 
      imports: [FormsModule], 
      //CUSTOM_ELEMENTS_SCHEMA to solve html elements issues 
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ], 
      providers: [Renderer] 
     }).compileComponents().then(() => { 
      fixture = TestBed.createComponent(TitlebarSearch);    
      titlebarComponent = fixture.componentInstance 
     }); 

    })); 

    //specs 
    it('should send the text to detect the change', async((done) => {   
     const text = "Changed text"; 
     titlebarComponent.doSubmit(text); 
     fixture.detectChanges(); 
     titlebarComponent.searchChange.subscribe(textRecived => { 
      expect(textRecived).toEqual(text); 
      done(); 
     })  
    }));   
}); 

的doSubmit方法中,當輸入文本已經被稱爲改變。然後,prepareSearchInput訂購了該主題以獲得具有去抖動的下一個並輸出相同的文本。

我不知道測試中的錯誤在哪裏,但覆蓋範圍從未涵蓋訂閱代碼。互聯網上的例子並沒有幫助我。

回答

0

我有同樣的問題,但從@jonrsharpe得到了答案:Unit test Angular 2 service subject

在調用next()之前,您需要在測試中早些時候聲明您的主題訂閱。如果重新排序是這樣,它應該工作:

it('should send the text to detect the change', async((done) => {   
    titlebarComponent.searchChange.subscribe(textRecived => { 
     expect(textRecived).toEqual(text); 
     done(); 
    }) 
    const text = "Changed text"; 
    titlebarComponent.doSubmit(text); 
    fixture.detectChanges(); 
}));  

的問題,根據約翰,是你的主題沒有任何重播/緩衝行爲。

相關問題