在 Angular 单元测试中定义时未定义的对象

undefined object when defined in Angular Unit testing

我正在研究我的测试环境,并试图通过在单元测试期间未定义 oidc-client 来解决单个用户配置文件的问题。

我试过 BeforeEach 方法 async 没有帮助,我也尝试过重组我的 AuthService

这是我从测试组件中得到的错误:

ResourcesCardComponent > should create

Failed: Cannot read property 'profile' of undefined

授权服务

import { Injectable } from '@angular/core';
import { UserManager, User, WebStorageStateStore } from 'oidc-client';
import { BehaviorSubject } from 'rxjs';
import { ConfigAssetLoaderService } from '../config-asset-loader.service';
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private _userManager: UserManager;
  public _user: User;
  public isLoggedInSubject$ = new BehaviorSubject<any>(this._user);
  isLoggedIn = this.isLoggedInSubject$.asObservable();

  constructor(private configService: ConfigAssetLoaderService) {
    const config = {};
    this.configService.loadConfiguration().subscribe(response => {
      config['authority'] = response.authority;
      config['client_id'] = response.client_id;
      config['redirect_uri'] = response.redirect_uri;
      config['scope'] = response.scope;
      config['response_type'] = response.response_type;
      config['loadUserInfo'] = response.loadUserInfo;
      config['userStore'] = new WebStorageStateStore({store: window.sessionStorage});
      config['metadata'] = {
        issuer: response.issuer,
        authorization_endpoint: response.authorization_endpoint,
        userinfo_endpoint: response.userinfo_endpoint,
        jwks_uri: response.jwks_uri,
        end_session_endpoint: response.end_session_endpoint
      };
      config['signingKeys'] = response.signingKeys;
      config['extraQueryParams'] = {
        resource: response.claimsApiResourceId
      };
      this._userManager = new UserManager(config);
      this._userManager.getUser().then(user => {
        if (user && !user.expired) {
          this._user = user;
          this.isLoggedInSubject$.next(user);
        }
      });
    });
  }
}

AuthService 非常标准,这个问题的所有重要部分都在构造函数中。

使用此服务的相关组件如下:

import { Component, Input } from '@angular/core';
import { ActionLink } from '../../shared/models/actionlink';
import { AuthService } from '../../core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'thrive-resources-card',
  templateUrl: './resources-card.component.html',
  styleUrls: ['./resources-card.component.scss']
})
export class ResourcesCardComponent {

  @Input() public actionLinks: ActionLink[];

  public firstName$: Observable<string>;

  constructor(private authService: AuthService) {
    this.firstName$ = this.authService.isLoggedInSubject$.pipe(
      map(response => response.profile.unique_name.replace(/\s+/, '').split(',')[1])
    );
  }
}

这里也是 ResourceCardComponent 的测试组件:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ResourcesCardComponent } from './resources-card.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ActivatedRoute, RouterModule } from '@angular/router';
import { ResourcesCardContainerComponent } from './resources-card-container/resources-card-container.component';

const fakeRoute = {
  snapshot: {
      data: {
        actionLinks: []
      }
  }
};

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        ResourcesCardComponent,
        ResourcesCardContainerComponent
      ],
      imports: [
        RouterModule,
        HttpClientTestingModule
      ],
      providers: [
        {
          provide: ActivatedRoute,
          useFactory: () => fakeRoute
        }
      ]
    }).compileComponents();
  }));

  beforeEach(async(() => {
    fixture = TestBed.createComponent(ResourcesCardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

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

您使用

启动您的服务
public isLoggedInSubject$ = new BehaviorSubject<any>(this._user)

因为 this._user 未定义。

然后在你的组件中,你想要 response.profile.unique_name.replace(/\s+/, '') ...

BUT this.authService.isLoggedInSubject$ return 作为第一个值 undefined。这就是您出现此错误的原因。

您应该将您的服务模拟为 return 一个可观察的 of({profile:{unique_name:'some name'}}) 或者用更好的数据启动您的用户。

spyOn(authService , 'isLoggedInSubject$').and.returnValue(of({profile:{unique_name:'some name'}}))