首页 > 解决方案 > 如何测试异步函数中设置的变量?

问题描述

我试图在执行异步函数后测试变量的值,但是当我尝试读取它时它是一个空数组(变量应该有一个包含对象的数组),我还放了一些 console.log( ) 在函数内部,它工作正常。

这是我第一次使用 Jasmine 和 Karma,所以任何帮助都可以。

我的组件内的功能

async refresh() {
let requestUserProfile;
let data
// this._fuseSplashScreenService.hide();

// this.showLoading('Cargando documentos...');

//requestUserProfile = this.getUserProfile();
this._restService.getDocumentsLimit(100, 1, undefined).subscribe((documents: any) => {
    //Here is just a part of this function
    this.moreData = documents.data;
});

}

变量 moreData 是我一直在尝试测试的变量。

测试代码;

describe('DashboardComponent', () => {
  let component: DashboardComponent;
  let fixture: ComponentFixture<DashboardComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [HomeModule, HttpClientModule, RouterTestingModule, NoopAnimationsModule, MatDialogModule ],
      declarations: [ DashboardComponent ]
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(DashboardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  //This is the one 
  it('should have info', async () =>{
      await component.refresh();
      console.log(component.moreData);
      //expect(component.moreData).not.toBe(null)
  })
});

标签: angularunit-testingkarma-jasmine

解决方案


问题不在于异步功能或其他东西。在您的测试脚本中,您需要做的是模拟服务并返回一些值,然后它将自动覆盖该变量。

这是您需要做的:

////////////////// Use Injectable and create a mock-service;

@Injectable()
class MockService extends RestService {
  ////////////////////// Mock your method here
  getDocumentsLimit() {
    return of({ 
        data: {
             // You know what response comes here, so use that here;
             someData: 'someDataValue'
        }
    }
  }
}

describe('DashboardComponent', () => {
  let component: DashboardComponent;
  let fixture: ComponentFixture<DashboardComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [HomeModule, HttpClientModule, RouterTestingModule, NoopAnimationsModule, MatDialogModule ],
      declarations: [ DashboardComponent ],
      ///////////////// ADD THIS LINE IN THE PROVIDERS /////////////
      providers: [
          {
            provide: RestService,
            useClass: MockService
          }
      ] 
    })
    .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(DashboardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  //This is the one 
  ////////////////////// YOUR TEST CASE WILL BECOME THIS
  it('should have info', () =>{
      spyOn(component, 'refresh').and.callThrough();
      component.refresh();
      expect(component.refresh).toHaveBeenCalled();
  })
});

推荐阅读