Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Test service subscribe on submit

How can i coverage test of submit action with subscribe event? i have this:


onSubmit() {
    this.myService.myMethod(value)
      .subscribe((result: any) => {
        console.log(result);
      },
        error => {
          console.log(error);
        },
        () => {
          console.log('completed);
        }
      );
}

test

it('should test submit',
    inject([myService, XHRBackend], (myService: any, mockBackend: any) => {
      const mockResponse = {
        error: false,
        msg: `Completed`
      };
      mockBackend.connections.subscribe((connection: any) => {
        connection.mockRespond(new Response(new ResponseOptions({
          body: JSON.stringify(mockResponse)
        })));
      });
      myService.myMethod().subscribe(() => { });
    }));

My test coverage show that i haven't tested the subscribe lines.

like image 944
BryGom Avatar asked Nov 20 '25 12:11

BryGom


1 Answers

There are few flaws in the component code of onSubmit. How can you test the outcome when you are just doing console.log etc. You need to handle some kind of flag and show/hide spinner or provide some error/success message. Then you can test the function with error and success. For example:

onSubmit() {
    this.showSpinner = true;
    this.myService.myMethod(value)
      .subscribe((result: any) => {
        this.msg = 'success';
      },
        error => {
          this.msg = 'error';
        },
        () => {
          this.showSpinner = false;
        }
      );
}

in test file:

class MySvcMock{
  myMethod() { return of('someVal')}
}

beforeEach(async(() => {
    TestBed.configureTestingModule({
       provider: [{provide: MyService, useClass: MySvcMock}]        
    }).compileComponents();
...
...

it('should set success msg on submit',()=>{
   component.msg = '';
   component.onSubmit();
   expect(component.msg).toBe('success');
   expect(component.showSpinner).toBeFalsy();
})

it('should set error msg on submit error',()=>{
   component.msg = '';
   spyOn(component.myService,'myMethod').and.returnValue(throwError('some error msg'));
   component.onSubmit();
   expect(component.msg).toBe('error');
   expect(component.showSpinner).toBeFalsy();
})

You can refer to my series of article which can help you get more familiar with Karma.

  1. Intro to Karma. check the links at the bottom of article
  2. This is the one which will help you in this scenario
like image 166
Shashank Vivek Avatar answered Nov 22 '25 00:11

Shashank Vivek