2

请帮帮我。

我正在迁移到 Jest 以运行 ANGULAR 的单元测试,但是在执行时出现错误:

FAIL 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 对我不起作用。

当我与 Karma 一起跑步时,它可以工作

这是测试:

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”,

4

1 回答 1

1

解决您的问题

为了使您的设置顺利运行,您必须在全局某处初始化 AuthenticationContext。我假设这发生在您代码中的浏览器中,方法是在您的index.htmlpolyfills.ts.

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 测试指南和笑话文档。

干杯和快乐的编码!

于 2020-11-15T13:50:52.007 回答