簡體   English   中英

Jasmine Angular 帶訂閱的單元測試

[英]Jasmine Angular Unit testing with subscribe

------服務文件-----

postStatus(status: String) {
    return this.http
        .post(url, null, {
          headers: new HttpHeaders({"Content-Type": "application/json"}),
          observe: "response"
        })
        .subscribe(
            responseDate => {
              console.log(responseDate)
              this.statusUpdated.next(status);
            },
            error => {
              if (status === "Z") this.statusUpdated.next("ZERROR")
              else this.statusUpdated.next("YERROR")
            })
  }

----- 規格文件 ---------

const errorResponse = new HttpErrorResponse({
  error: 'test 404 error',
  status: 404, statusText: 'Not Found'
});


it('postStatus should return error and update status to error to ZERROR' ,() =>{
    httpCientSpyPost = jasmine.createSpyObj('http', ['post']);
    service  = new ChangelogService(<any>httpCientSpyPost,null,null,new PostMessageService());
    let updatedStatus:string = '';


    httpCientSpyPost.post.and.returnValue(of(errorResponse));
    service.statusUpdated.subscribe((status:string) => {updatedStatus=status});

    service.postStatus('Z');

    expect(httpCientSpyPost.post.calls.count()).toBe(1, 'one call');
    expect(updatedStatus).toBe('ZERROR');
});

---------錯誤我得到------------

錯誤:

Expected 'Z' to be 'ZERROR'.

它不會出錯塊。 我在這里錯過了什么嗎?

您正在返回錯誤 object 而不會導致可觀察到的錯誤,因此它正在執行成功路徑。 嘗試將returnValue替換為以下內容:

httpCientSpyPost.post.and.returnValue(throwError(errorResponse));

這將導致 observable 進入錯誤路徑。 您需要從 rxjs 導入throwError

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM