Zuckjet
Zuckjet

Reputation: 847

unit test for Angular service when service doesn't return an Observable?

I have looked at the doc to learn how to test an http request, but I could not figure out how to unit test a service like below from the docs.

class service {

data$: BehaviorSubject<any> = new BehaviorSubject<>(any);

getDatas(): Observable<any> {
    this.http.get(url).subscribe((response) => {
       this.data$.emit(response);
    });
    // if return a observable will be like:
    // return this.http.get(url).

  }

}

How can i test the service above if it's method doesn't return an Observable?

Upvotes: 0

Views: 462

Answers (1)

ccamac
ccamac

Reputation: 516

The comment from The Head Rush is right. Here is a code example I had handy for this.

service

export class SomeService {
  constructor() {}

  goDoSomething(): void {
      console.log('I did something');
  }

}

test

    describe('testing goDoSomething method', () => {
        it('should call console log', () => {
            spyOn(console, 'log'); // console is the object, and log is the method I expect to be called
            service.goDoSomething();
            expect(console.log).toHaveBeenCalled();
        });
    });

Upvotes: 1

Related Questions