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

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

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

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

ResourcesCardComponent > should create

Failed: Cannot read property 'profile' of undefined

AuthService

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();
  });
});
wx0806 回答:在角度单元测试中定义时未定义的对象

您通过

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

因为this._user未定义。

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

BUT this.authService.isLoggedInSubject$作为第一个值undefined返回。这就是为什么您有此错误。

您应该嘲笑您的服务以返回可观察的of({profile:{unique_name:'some name'}}),或者使用更好的数据来启动用户。

spyOn(authService,'isLoggedInSubject$').and.returnValue(of({profile:{unique_name:'some name'}}))
本文链接:https://www.f2er.com/3149276.html

大家都在问