错误:对于条件“匹配URL:api / xyz”,预期有一个匹配请求,但找不到

时间:2019-10-10 17:35:18

标签: angular typescript unit-testing jasmine

我正在编写单元测试,以检查是否调用了api。要进入调用api的函数,我必须填写将从服务中获取的值。

这是代码段

component.ts

ngOnInit() {

  this.subscription = this.topToolBarService.change.subscribe(customer => {
    this.filter.customerNumber = customer.customerNumber;
    this.filter.customerName = customer.customerName;
    this.customerid = customer.customerNumber;
    this.getData();// here (1)
 });

  let customer = this.topToolBarService.getCustomer();
    if (customer == null) {
     //code gets blocked here
    } else {
      this.filter.customerNumber = customer.customerNumber;
      this.filter.customerName = customer.customerName;
      this.customerid = customer.customerNumber;
      this.getData();   //here (2) 
    }
}

 getData() {
  this.http.post...
   .....calls api
 }

service.ts

import { EventEmitter, Injectable, Output } from "@angular/core";

@Injectable()
export class TopToolBarService {

  customer = null;

  @Output() change: EventEmitter<string> = new EventEmitter();

   getCustomer() {
    return this.customer;
  }

}

component.spec.ts

it('should fetch all the activated accounts from cosmos using /api/users', () => {

    spyOn(component, 'getData').and.returnValue(of(response));  
    //attempt to somehow get passed through subscribe  
    fixture.detectChanges();
    component.filter.customerName = "123";
    fixture.detectChanges();
    component.filter.customerNumber = "xyz";
    fixture.detectChanges(); 

    const req = _HttpTestingController.expectOne('api/xyz');//test fails here
  Error: Expected one matching request for criteria "Match URL: api/xyz", found none.
    expect(req.request.method).toBe("POST");
    let responseData = component.records;
    req.flush({status:"SUCCESS","data":responseData});

  }) 

我将以某种方式模拟更改。订阅并调用此代码块中调用的函数,或使服务方法返回除null以外的有效客户以调用该函数。

我如何使测试通过?

谢谢

0 个答案:

没有答案