使用Jest运行测试时,Adal.service.ts在角度上对我不起作用

问题描述

请帮助我。

我要迁移到Jest来运行ANGULAR的单元测试,但是执行时出现错误

失败 src / app / modules / dashboard / components / navbar / navbar.component.spec.ts
测试套件无法运行

ReferenceError: AuthenticationContext is not defined

   6 | 
   7 | declare var AuthenticationContext: adal.AuthenticationContextStatic;
>  8 | const createAuthContextFn: adal.AuthenticationContextStatic = AuthenticationContext;
     |                                                               ^
   9 | 
  10 | @Injectable()
  11 | export class AdalService {

  at Object.<anonymous> (src/app/core/authentication/adal.service.ts:8:63)
  at Object.<anonymous> (src/app/core/authentication/adal-access.guard.ts:3:1)
  at Object.<anonymous> (src/app/modules/dashboard/components/navbar/navbar.component.spec.ts:5:1)

测试套件:1个失败,总共1个

当我用Jest运行测试时,Adal.service.ts在角度上对我不起作用。

当我与业力一起运作时,它会起作用

这是测试:

import { Store } from '@ngrx/store';
import { RouterTestingModule } from '@angular/router/testing';
import { MatMenuModule } from '@angular/material/menu';
import { AdalConfigService } from './../../../../core/authentication/adal-config.service';
import { AdalAccessGuard } from './../../../../core/authentication/adal-access.guard';
import { AdalService } from '@authentication/adal.service';
import { environment } from '@env/environment';
import { APP_CONfig } from '@app/app.config';
import { async,ComponentFixture,Testbed } from '@angular/core/testing';

import { NavbarComponent } from './navbar.component';

describe('NavbarComponent',() => {
    let component: NavbarComponent;
    let fixture: ComponentFixture<NavbarComponent>;

    beforeEach(async(() => {
        Testbed.configureTestingModule({
            declarations: [NavbarComponent],imports: [
                RouterTestingModule,MatMenuModule
            ],providers: [
                {
                    provide: Store,useValue: {
                        dispatch: jest.fn(),pipe: jest.fn()
                    }
                },AdalService,AdalConfigService,AdalAccessGuard,{
                    provide: APP_CONfig,useValue: {
                        apiEndpoint: environment.apiEndPoint,clientId: environment.azureActiveDirectory.clientId,tenantId: environment.azureActiveDirectory.tenantId,resource: environment.azureActiveDirectory.resource,redirectUri: environment.azureActiveDirectory.redirectUri
                    }
                }]
        })
            .compileComponents();
    }));

    beforeEach(() => {
        let mockADalerror;
        let mockAdal;
        fixture = Testbed.createComponent(NavbarComponent);
        component = fixture.componentInstance;
        mockADalerror = false;
        mockAdal = {
            userName: 'xxx',profile: {
                aud: 'xxx',}
        };
    });

    it('should create',() => {
        expect(component).toBeTruthy();
    });

});
  • 经过组件测试:
import { AdalService } from '@authentication/adal.service';
import { Component,OnInit } from '@angular/core';

@Component({
  selector: 'app-navbar',templateUrl: './navbar.component.html',styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit {

  public name;
  public surname;
  public email;

  constructor( private adalService: AdalService ) { }

  ngOnInit() {
    this.loadUserInfo(this.adalService.userInfo);
  }

  onlogout(): void {
    this.adalService.logout();
  }

  loadUserInfo(adalUser: any): void {
    if (adalUser) {
      this.name = XXX;
      this.email = XXX;
    } else {
      this.name = 'No disponible';
      this.email = 'No disponible';
    }
  }

}

这是ADAL的服务

import { Injectable } from '@angular/core';
import { Observable,Subscriber } from 'rxjs';
import { retry } from 'rxjs/operators';
import { AdalConfigService } from './adal-config.service';
import { adal } from 'adal-angular';

declare var AuthenticationContext: adal.AuthenticationContextStatic;
const createAuthContextFn: adal.AuthenticationContextStatic = AuthenticationContext;

@Injectable()
export class AdalService {
    private context: adal.AuthenticationContext;
    constructor(private configService: AdalConfigService) {
        this.context = new createAuthContextFn(configService.adalSettings);
    }
    login() {
        this.context.login();
    }
    logout() {
        this.context.logout();
    }
    get authContext() {
        return this.context;
    }
    handleWindowCallback() {
        this.context.handleWindowCallback();
    }
    public get userInfo() {

        return this.context.getCachedUser();
    }
    public get accesstoken() {
        return this.context.getCachedToken(this.configService.adalSettings.clientId);
    }
    public get isAuthenticated() {
        return this.userInfo && this.accesstoken;
    }

    public isCallback(hash: string) {
        return this.context.isCallback(hash);
    }

    public getLoginError() {
        return this.context.getLoginError();
    }

    public getAccesstoken(endpoint: string,callbacks: (message: string,token: string) => any) {

        return this.context.acquiretoken(endpoint,callbacks);
    }

    public acquiretokenResilient(resource: string): Observable<any> {
        return new Observable<any>((subscriber: Subscriber<any>) =>
            this.context.acquiretoken(resource,(message: string,token: string) => {
                token ? subscriber.next(token) : subscriber.error(message);
            })
        ).pipe(retry(3));
    }
}

我正在使用以下版本:“ adal-angular”:“ ^ 1.0.17”,

解决方法

解决您的问题

要使安装顺利进行,必须在全局某处初始化AuthenticationContext。我认为这是通过在您的index.htmlpolyfills.ts中加载一些adal脚本在您的代码的浏览器中发生的。

Jest不会加载这些文件,因此不会在任何地方初始化AuthenticationContext。

使用变量declare var AuthenticationContext: adal.AuthenticationContextStatic的声明,您告诉TypeScript:“我保证我会在其他地方全局初始化此变量”,但看来您不是在Jest运行中这样做。

解决方案是在需要的测试文件中导入用于初始化AuthenticationContext的脚本,或者在需要的文件中手动进行脚本:

// 1. Initialize Variable
// not sure if you can initialize it like this,see the adal docs or source code
globalThis.AuthenticationContext = new AuthenticationContext();

// 2. Tell TypeScript compiler about this variable
declare const AuthenticationContext: adal.AuthenticationContextStatic;

单元测试

您谈论的是单元测试,但是您的测试看起来并不像单元测试,因为您没有以孤立的方式对其进行测试。

如果要按单元测试每个组件,则完全不应实例化AuthenticationContext来测试NavBar。并非来自NavBar内部的所有其他组件和对象都应被模拟并作为虚拟对象提供。这样也可以间接解决您的问题。

要更好地理解这一点,请查看《 Angular测试指南》和jest文档。

欢呼和快乐的编码!