使用Jasmine测试异步调用期间发生的情况

时间:2019-04-29 06:56:01

标签: javascript angular typescript jasmine

我是茉莉的新手。我需要测试以下Angular组件:

<form (ngSubmit)="onSubmit()" *ngIf="!(paycheck$ | async)">
    <!-- fields -->
    <button type="submit">Submit</button>
</form>

<div class="pageloader" [class.is-active]="loading$ | async"></div>

<div class="panel" *ngIf="response$ | async as response">
    <!-- fields -->
</div>

该组件具有一个表单,其中包含许多字段和一个提交按钮;在提交时,组件启动一个http请求,隐藏表单,等待1000毫秒并显示一个加载微调器;当收到响应时,该组件将隐藏微调框并显示响应的内容。这是相关的TypeScript代码:

export class MyComponent implements OnInit {

  loading$: Subject<boolean>;
  paycheck$: Subject<any>;

  constructor(private service: MyService) {}

  ngOnInit() {
    this.loading$ = new Subject();
    this.response$ = new Subject();
  }

  onSubmit() {

    timer(1000).pipe(
      takeUntil(this.response$)
    ).subscribe(response => {
      this.loading$.next(true);
    });

    this.service.get().pipe(
      take(1),
    ).subscribe(response => {
      this.loading$.next(false);
      this.response$.next(response);
    });

  }

}

我可以使用以下Jasmine测试来测试服务发送响应时发生的情况:

beforeEach(async(() => {
    TestBed.configureTestingModule({
        imports: [HttpClientModule],
        declarations: [MyComponent]
    }).compileComponents();
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    service = TestBed.get(MyService);
    backend = TestBed.get(HttpClient);
}));

it('should receive data on click', () => {
    spyOn(backend, 'get').and.returnValue(of({"key": "value"}));
    component.response$.subscribe(r => expect(r).toEqual({"key": "value"}));
    component.onSubmit();
});

该测试之所以有效,是因为Jasmine等待异步请求完成。但是,在服务发送响应之前,我不知道如何测试正在发生的事情。我想编写一个发出请求的测试,等待1000毫秒,并期望loading$已收到true。我该怎么办?

0 个答案:

没有答案