super IT guy
super IT guy

Reputation: 313

Angular unit test observable was returned

How can you write a test to make sure that an observable was called?

Example: obj: any = {func: () => this.obs$}

I want to write a test that ensures that obj.func returns this.obs$.

i have tried the following:

it('should demonstrate obs is returned', () => {
    const spy = spyOn<any>(component, 'obs$').and.returnValue(of('test'));

    const ret = component.obj.func();

      expect(spy).toHaveBeenCalled();

// 2nd attempt

expect(ret).toEqual('test');
 })

Neither of these worked. Any help would be most appreciated.

Upvotes: 0

Views: 96

Answers (2)

super IT guy
super IT guy

Reputation: 313

Wanted to respond in a separate answer, although AliF50's answer worked, and thank you for the help, they were not correct about the spy. It worked with the spy also, meaning:

it('should demonstrate obs is returned', (done) => { // add done callback here
  spyOn<any>(component, 'obs$').and.returnValue(of('test'));
  const ret = component.obj.func();
  ret.subscribe(value => { 
    expect(value).toEqual('test');
    done();
  });
});

Also works.

However, I found another solution that also works, and is shorter:

it('should demonstrate obs is returned', () => {
    expect(component.obj.func()).toEqual(component.obs$);
 })

my mistake was trying to do this:

component.obs$ = of('test'); 

expect(component.obj.func()).toEqual(of(test));

//or

expect(component.obj.func()).toEqual('test');

Which both do not work.

Hope this helps someone else.

Upvotes: 0

AliF50
AliF50

Reputation: 18889

You can't spyOn obs$ assuming it's an observable and not a function. You can only spy on functions.

Try:

it('should demonstrate obs is returned', (done) => { // add done callback here
  component.obs$ = of('test'); // assign obs$ to observable of 'test'
  const ret = component.obj.func();
  ret.subscribe(value => { // subscribe to the observable that previous function gives.
    expect(value).toBe('test');
    done(); // call done to tell Jasmine that you are done with the tests
  });
});

Upvotes: 1

Related Questions