首页 > 解决方案 > Angular 中 Auth0 文件的单元测试

问题描述

以下是用于应用程序身份验证的 auth0 服务文件。 从'auth0-js'导入*作为auth0; 使用 auth0 模块我创建了用于测试 auth0 服务文件的存根文件。单元测试在 Jasmine Karma 中完成。测试通过但没有任何覆盖。因此毫无用处。请帮助找出单元测试代码中的错误。

Auth0 服务文件

@Injectable()
export class AuthService {
  private _Auth0 = new auth0.WebAuth({
    clientID: AUTH_CONFIG.CLIENT_ID,
    domain: AUTH_CONFIG.CLIENT_DOMAIN,
    responseType: 'token id_token',
    redirectUri: AUTH_CONFIG.REDIRECT,
    audience: AUTH_CONFIG.AUDIENCE,
    scope: AUTH_CONFIG.SCOPE
  });

  userProfile: UserProfile;
  accessToken: string;
  expiresAt: number;
  loggedIn: boolean;
  loggedIn$ = new BehaviorSubject<boolean>(this.loggedIn);

  constructor(public router: Router) {
  }

  login() {
    this._Auth0.authorize({ connection: 'value ....' });
  }

  handleLoginCallback() {
    this._Auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken) {
        window.location.hash = '';
        this.accessToken = authResult.accessToken;
        this.getUserInfo(authResult);
        this.router.navigate(['/home']);
      } else if (err) {
        console.error(`Error: ${err.error}`);
      } else {
        console.log('Authentication not successful');
      }
    });
  }

  getUserInfo(authResult) {
    this._Auth0.client.userInfo(authResult.accessToken, (err,  profile)  =>  {
      this._setSession(authResult,  profile);
    });
    if  (authResult.idTokenPayload.user_metadata) {   
      let decodedToken = jwt_decode(authResult.accessToken);
      decodedToken["https://api.test.net/roles"].forEach(role => {
        if (role == "COMMON_EXCEPTIONHANDLER_UPDATER") {
          localStorage.setItem("perm", 'write');
        }
      }); 
      localStorage.setItem('loggedInUser',
     `${authResult.idTokenPayload.user_metadata.username}@${authResult.idTokenPayload.name}`);
    }
  }

  private _setSession(authResult, profile) {
    this.expiresAt = authResult.expiresIn * 1000 + Date.now();
    this.accessToken = authResult.accessToken;
    this.userProfile = profile;
    this._setLoggedIn(true);
  }

  logout() {
    this._Auth0.logout({
      returnTo: environment.returnTo,
      clientID: AUTH_CONFIG.CLIENT_ID
    });
    localStorage.removeItem('loggedInUser');
  }

  private _setLoggedIn(value: boolean) {
    this.loggedIn$.next(value);
    this.loggedIn = value;
  }

  get authenticated(): boolean {
    return (Date.now() < this.expiresAt) && this.loggedIn;
  }
}

**Following is the stub file created**

import { Observable, of } from 'rxjs';
export class Auth0SecurityServiceStub {
    authorize() {}

    parseHash() {
        return { user: 'bob', idToken: 'token' };
    }

    logout() { return of(true);}

    authenticated() {
        return true;
    }

    accessToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVC";

    userProfile: {
        "sub": "waad|nwr1ZvxhR3Bdpn4Xapd9i9F_x48y0cdrqQ5mTQeNjjI",
        "given_name": "test1",
        "family_name": "test3",
        "nickname": "M@test.com",
        "name": "test",
        "picture": "https://s.gravatar.com/avatar/0cd89133dd90b50a34e97da7d146cc45?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fmm.png",
        "updated_at": "2021-08-03T15",
        "email": "test@test.com",
        "email_verified": true
    };
    expiresAt = '1628012228162';
    loggedIn = true;
}

请帮助如何让代码覆盖适当的测试。

标签: angularunit-testingkarma-jasmineauth0karma-coverage

解决方案


推荐阅读