Devvvvv
Devvvvv

Reputation: 92

How to test console value to satisfy unit test?

For a Non-Profit class that we're putting together, we are trying to validate the console value to see if a function executed successfully. This is supposed to be a small, simple test but I've hit a wall. :-) Any help is appreciated. P.S. We're open to new packages if it makes things more efficient and simpler.

Here's the pseudo-ish attempt:

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

Upvotes: 1

Views: 243

Answers (1)

Anand Bhushan
Anand Bhushan

Reputation: 783

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

Upvotes: 1

Related Questions