問題描述
如何測試控制台值以滿足單元測試? (How to test console value to satisfy unit test?)
對於我們正在組合的非營利類,我們正在嘗試驗證控制台值以查看函數是否成功執行。這應該是一個小而簡單的測試,但我碰壁了。:‑) 任何幫助表示讚賞。PS 如果新軟件包能讓事情變得更高效、更簡單,我們願意接受。
這是偽嘗試:
it('should match value in console', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.console.log.textContent).toEqual(
'CONSOLE MESSAGE',
);
});
參考解法
方法 1:
If you need to unit test your console log, you can try something like this:‑
it('test', () => {
const fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
spyOn(console, 'log');
component.methodToBeTested(); // call the method which has console.log
expect(console.log).toHaveBeenCalledWith('log message'); // assuming console.log('log message') is in methodToBeTested()
});
(by Devvvvv、Anand Bhushan)