0

我正在研究一个主要在 onNgInit() 方法上完成其工作的组件:

      stage = '';
      onNgInit(){
      const thus : any = this;
      this.stage = "start';
      this.uniService.dataExists().then(result=>{
       // the data exists. get ProductTypes
       that.stockService.productTypes().subscribe(proTypes=>{

        vm.stage = "Setting status to products";
        proTypes.map(product....);
      });
     });
    }

现在在我的测试中,我相信,由于代码是 onNgInit,stage 的值仍然是“start”。我想知道是否有办法观察变量的值变化,或者更好的是,特定变量的最终值?

import { async, ComponentFixture, TestBed } from "@angular/core/testing";
import { TrackerComponent } from "./tracker.component";

describe("TrackerComponent", () => {
  let component: TrackerComponent;
  let fixture: ComponentFixture<TrackerComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [TrackerComponent]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TrackerComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  //
  it("should is created", () => {
    expect(component).toBeTruthy();
    expect(component.stage).toEqual('start');// want to track the changes

  });

});
4

2 回答 2

0

我真的不明白你为什么在它的 ngOnInit 时调用它 onNgInit 但这里有一个假设它是一个类型的答案:

您需要重写一些 ngOnInit 以返回某种值。

  public async ngOnInit(): Promise<void>{
      const thus : any = this;
      this.stage = "start';
      const result = await this.uniService.dataExists();
       // the data exists. get ProductTypes
      const proTypes = await (that.stockService.productTypes().toPromise());
      this.stage = "Setting status to products";
      proTypes.map(product....);
  }

因此,在您的 UT 中,您可能会遇到以下情况:

 it("should is created", (done) => {
    expect(component.stage).toEqual('start');
    component.ngOnInit().then(() =>{
        expect(component.stage).toEqual('Setting status to products');          
        done();
    });
  });

要么是这个,要么是从 Promise 切换到 observables。

此外,您不应该只相信功能会执行。测试时,您应该测试每个停止及其进展。

于 2019-11-15T12:09:34.050 回答
0

您需要在检查条件之前将异步调用uniService.dataExists().then与. 这可以使用第二个函数中的and来完成。stockService.productTypes().subscribeexecfakeAsyncflushbeforeEach

import { fakeAsync, flush } from '@angular/core/testing';
...
beforeEach(fakeAsync(() => {
    fixture = TestBed.createComponent(TrackerComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    flush();
}));
于 2019-11-15T11:50:07.957 回答