如何对nSwag Angular客户端进行单元测试

时间:2019-04-20 15:06:09

标签: angular ngxs nswag

我正在尝试为使用nswag生成的客户端编写一个简单的单元测试,它看起来很

it('it create a call create on the api if new household', async(() => {
   const newHousehold = new Household();
   newHousehold.name = 'Test Household';
   store.dispatch(new SaveHousehold(newHousehold));

   const req = httpTestingController.expectOne('http://localhost:57461/api/Households');

   req.flush(newHousehold);

   expect(req.request.method).toEqual('POST');
}));

但是出现以下错误:

Failed: Automatic conversion to Blob is not supported for response type

我尝试了几种方法将newHousehold转换为Blob,但是它始终返回空白或引发其他错误。那么我该如何测试该客户端?

仅供参考,我还在商店中使用NGXS,因此这就是为什么它调用store.dispatch并触发http请求的原因。

这是操作代码

@Action(SaveHousehold)
 public saveHousehold(
   { dispatch }: StateContext<HouseholdStateModel>,
   payload: SaveHousehold
 ) {
let subscription: Observable<Household>;

if (payload.household.id) {
  subscription = this.service.update(
    payload.household.id,
    payload.household
  );
} else {
  subscription = this.service.create(payload.household);
}

subscription.subscribe(result => {
  if (!payload.household.id) {
    dispatch(new LinkToExistingHousehold(result.id));
  }
},error=>{
  console.error(error);
});
 }

这是service.create

的代码
create(entity: Household): Observable<Household | null> {
    let url_ = this.baseUrl + "/api/Households";
    url_ = url_.replace(/[?&]$/, "");

    const content_ = JSON.stringify(entity);

    let options_ : any = {
        body: content_,
        observe: "response",
        responseType: "blob",
        headers: new HttpHeaders({
            "Content-Type": "application/json", 
            "Accept": "application/json"
        })
    };

    return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => {
        return this.processCreate(response_);
    })).pipe(_observableCatch((response_: any) => {
        if (response_ instanceof HttpResponseBase) {
            try {
                return this.processCreate(<any>response_);
            } catch (e) {
                return <Observable<Household | null>><any>_observableThrow(e);
            }
        } else
            return <Observable<Household | null>><any>_observableThrow(response_);
    }));
}

问题似乎是因为在创建中指定了responseType

1 个答案:

答案 0 :(得分:0)

解决方案是按Blob刷新响应,如下所示:

req.flush(new Blob([JSON.stringify(newHousehold)], { type: 'application/json' }));