首页 > 解决方案 > Jasmine:测试是否使用 HttpTestingController 调用 API

问题描述

我正在为 Angular 应用程序运行单元测试,单击按钮后,API 被调用,我正在测试是否调用了这个 API,并且还使用 HttpTestingController 请求方法!我正在使用 jasmine。

 <div class="form-group">
   <label class="col-sm-6 col-form-label" for="name">Customer Number</label>
   <input type="text" id="accountid" class="form-control col-sm-3" [(ngModel)]="record.accountid" (change)="daemonChanged(0)" name="accountid" required>
   <button id="loadbtn" (click)="loadCustomer()" class="col-sm-3 btn">Load</button>
 </div>  

在我的规格文件中

//tried both the ways to trigger click event it doesn't work
loadButton.triggerEventHandler('click',null);
loadButton.nativeElement.dispatchEvent(new Event('click'));
fixture.detectChanges();
let dummyResponse ={"status":"SUCCESS","data":{}}; 
let req2 = _HttpTestingController.expectOne('/api/accounts');//fails here
expect(req2.request.method).toBe("POST"); 

loadCustomer () {
this.http.post('/api/accounts', this.record) //function indeed calls this API!!!
.subscribe(res => {
..some logic...
});

标签: angulartypescriptunit-testingjasmine

解决方案


推荐阅读