Angular 5单元测试服务UPDATE方法

时间:2018-02-15 13:03:04

标签: javascript unit-testing typescript angular5

我正在使用步进器后退步骤和最后一步当用户点击完成时我调用了一个服务来更新我测试过的backStep()nextStep()方法的用户数据但我要测试{{1更新布尔值的方法。这是我的代码

P.S:如何测试更新数据并返回响应的服务?

控制器:

updateAdmin()

联合测试

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

提前致谢。

1 个答案:

答案 0 :(得分:0)

我对最新版本的Angular不实用,但在Angularjs上我使用spyOn来解决这个问题。 因此,请尝试spyOn以确保将调用该方法。 您必须在单独的specs文件中测试服务(adminService)。

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

您还可以使用spyOn模拟updateAdmin的响应,以模拟正确和失败的响应。

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