简体   繁体   English

Jasmine Angular 带订阅的单元测试

[英]Jasmine Angular Unit testing with subscribe

------Service file ------- ------服务文件-----

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")
            })
  }

----- Spec file --------- ----- 规格文件 ---------

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');
});

---------Error I am getting ------------ ---------错误我得到------------

Error:错误:

Expected 'Z' to be 'ZERROR'.

Its not going to error block.它不会出错块。 Am I missing something here?我在这里错过了什么吗?

You are returning the error object without causing an error in the observable, so it is executing the success path.您正在返回错误 object 而不会导致可观察到的错误,因此它正在执行成功路径。 Try replacing the returnValue with the following:尝试将returnValue替换为以下内容:

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

This will cause the observable to enter the error path.这将导致 observable 进入错误路径。 You will need to import throwError from rxjs.您需要从 rxjs 导入throwError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM