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'.

它不会出错。我在这里遗漏了什么吗?

您正在返回错误对象而不会在可观察对象中引起错误,因此它正在执行成功路径。尝试将 returnValue 替换为以下内容:

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

这会导致observable进入错误路径。您需要从 rxjs 导入 throwError