如何测试控制台值以满足单元测试?



对于我们正在组合的非营利类,我们正在尝试验证控制台值以查看函数是否成功执行。这应该是一个小而简单的测试,但我碰壁了。:-) 任何帮助,不胜感激。附言:如果新软件包使事情更有效率、更简单,我们对新软件包持开放态度。

这是伪尝试:

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',
);
});

如果您需要对控制台日志进行单元测试,可以尝试如下操作:

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()
});

最新更新