【问题标题】:Jasmine Angular Unit testing with subscribe带有订阅的 Jasmine Angular 单元测试
【发布时间】:2020-09-23 19:52:37
【问题描述】:

-----服务文件-----

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

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

【问题讨论】:

    标签: angular unit-testing jasmine karma-jasmine angular-unit-test


    【解决方案1】:

    您正在返回错误对象而不会导致 observable 发生错误,因此它正在执行成功路径。尝试将 returnValue 替换为以下内容:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      相关资源
      最近更新 更多