【问题标题】:why Jasmine is not returning fake data?为什么 Jasmine 不返回虚假数据?
【发布时间】:2018-07-31 03:47:58
【问题描述】:

我有一个调用服务类来执行某些操作的组件。服务类使用 httpClient 调用一个永恒的 api。我正在尝试按如下方式测试组件:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      providers: [SomeService],
    }).compileComponents();
    service = TestBed.get(SomeService);
  }));

 fit('should', async () => {
    fixture.detectChanges();
    const fakeHttpPromise = {
      success: function () { }
    };
    spyOn(service, 'save').and.callFake(function () {
      return fakeHttpPromise;
    });

    const textbox1 = fixture.debugElement.query(By.css('input[formControlName=control1]'));
    textbox1.nativeElement.value = 'value';

    const textbox2 = fixture.debugElement.query(By.css('input[formControlName=constrol2]'));
    textbox2.nativeElement.value = 'value';

    // here i Create model object using textbox1 and textbox2 value
    // This should not call actual service 
    component.Save(model);
    fixture.detectChanges();



    fixture.whenStable().then(() => {
      fixture.detectChanges();

      expect(service.save).toHaveBeenCalled();
    });
  });

这是组件保存点击:

Save(model: any) {
      this.Service.save(model)
        .then((res) => {
        }
  }

问题:为什么当间谍返回虚假承诺时调用实际服务?实际服务使用 httpclient,我不想实际调用它,而只是返回一个虚假的承诺。

【问题讨论】:

  • 你也可以添加组件代码吗?
  • 在这里删除fixture.detectChanges:fit('should', async () => { fixture.detectChanges();
  • 删除 fixture.dectectChanges() 没有帮助。有任何想法吗 ?组件保存点击已经提供。请看一看。

标签: angular karma-jasmine


【解决方案1】:

这是我解决这个问题的方法:

1) 更改了我的保存点击以从组件中的本地方法调用服务:

Save(model: any) {
      this.btnsave(model).then((res) => {
        }
  }

btnsave(model){
 return this.Service.save(model);
}

2) 将测试改为:

   fit('should', async () => {
        fixture.detectChanges();
        const fakeHttpPromise = Promise.resolve();
// spy on components method
        spyOn(component, 'btnsave').and.returnvalue(fakeHttpPromise);

        const textbox1 = fixture.debugElement.query(By.css('input[formControlName=control1]'));
        textbox1.nativeElement.value = 'value';

        const textbox2 = fixture.debugElement.query(By.css('input[formControlName=constrol2]'));
        textbox2.nativeElement.value = 'value';

        // here i Create model object using textbox1 and textbox2 value
        // This should not call actual service 
        component.Save(model);
        fixture.detectChanges();



        fixture.whenStable().then(() => {
          fixture.detectChanges();
// check on component method     
          expect(component.btnsave).toHaveBeenCalled();
        });
      });

【讨论】:

    猜你喜欢
    • 2013-08-26
    • 1970-01-01
    • 2014-02-03
    • 2012-08-27
    • 2014-09-07
    • 2021-11-19
    • 2011-06-07
    • 2015-10-05
    • 2013-11-09
    相关资源
    最近更新 更多