如何在Jamsine中的Observable中编写服务返回错误时的单元测试用例

时间:2019-07-03 16:36:31

标签: angular jasmine

我想在Service Observable返回Error时为Error条件编写单元测试用例。 我无法完成“代码覆盖率”中的错误情况。

login()
  {
      let username = this.loginForm.get('userName').value;
      let password = this.loginForm.get('password').value;
      let baseIP = this.baseIP;

      this.authenticationService.validateCredentials(username,password)
      .subscribe( () =>
                       {
                          // alert('authentication successful');
                        this.router.navigate(['']); // need to modify this
                       },
                       (error: any) => 
                       {
                           console.log(error);
                           alert('authentication is failed')
                       }
       );
 //Below is my Error testing test case.    
      it('Should throw an Error for Login case',(done:DoneFn)=>{
        spyOn(authenticationService,'validateCredentials').and.callFake((param)=>{
          return throwError({
            "Error":404
          })
        });

         const user="Admin";
        const pass="Admin";
        component.login();
        authenticationService.validateCredentials(user,pass).subscribe(
          ()=>{
            fail(error);
          }),
            (error: any)=>{
              expect(error).toBeDefined();
            }

0 个答案:

没有答案