简体   繁体   中英

Angular 5 Unit Testing Service UPDATE Method

I am using stepper back step next step and at last step when user clicks done I called a service to update user data I have tested backStep() and nextStep() methods however I want to test updateAdmin() method to update a boolean value. Here is my code

PS: How to test a service which UPDATE data and returns the response?

Controller:

backStep(step: number) {
this.currentStep = --step;
this.currentSlide.emit(this.currentStep);
}

nextStep(step: number) {
if (++step <= this.totalSteps.length) {
  this.currentStep = step;
  this.currentSlide.emit(this.currentStep);
} else {
  this.updateAdmin();
 }
}

updateAdmin() {
  const body = {
   is_admin: true
  }

this.adminService.updateAdmin(user_id, body).subscribe(
  (response) => {
    console.log(response);
   }
 );
}

Unite Tests

it('backStep() should decrement current step', () => {
  comp.backStep(2);
  expect(comp.currentStep).toEqual(1);
});

it('nextStep() should increment current step', () => {
  const start = 1;
  comp.totalSteps = Array.from(Array(4), (_, i) => start + i);
  comp.nextStep(1);
  expect(comp.currentStep).toEqual(2);
 });

it('Should call updateAdmin method and test mock service', () => {
  const start = 1;
  comp.totalSteps = Array.from(Array(4), (_, i) => start + i);
  comp.nextStep(4);
//when steps reached to max limit (4) I need to call a mock service which should update a field and return response, here I dont know how to test updateAdmin() method.
  });
});

Thanks in advance.

I'm not practical on latest version of Angular, but on Angularjs I use spyOn for this issue. So, try spyOn to be sure that method will be invoked. You have to test service (adminService) in separate specs file.

    spyOn(comp, 'updateAdmin');
    ...
    ...
    expect(comp.updateAdmin).toHaveBeenCalled();

You can also use spyOn to mock response of updateAdmin to simulate a right and fail response.

spyOn(comp,'updateAdmin').and.callFake(function(){
  var deferred = $q.defer();
  deferred.resolve('WANTED RESPONSE);
  return deferred.promise;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM