getting TypeError: Cannot read property 'get' of undefine when running karma test using injector

getting TypeError: Cannot read property 'get' of undefine when running karma test using injector

所以在我的 Karma 测试之一中,如下所示,它显示 TypeError: Cannot read 属性 'get' of undefine!

你能告诉我我做错了什么吗

import { async, ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { AlertsComponent } from './alerts.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { CUSTOM_ELEMENTS_SCHEMA, SimpleChange, SimpleChanges, Renderer2, Injector, INJECTOR } from '@angular/core';
import { AlertStore } from 'store-manager';
import { of, Observable, Observer } from 'rxjs';
import { IntlModule } from '@progress/kendo-angular-intl';

describe('Alerts Component', () => {
  let alertComponent: AlertsComponent;
  let fixture: ComponentFixture<AlertsComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AlertsComponent],
      imports: [HttpClientTestingModule, IntlModule],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      providers: [{ provide: AlertStore, useClass: MockAlertStore },Renderer2]
    }).compileComponents()
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AlertsComponent);
    alertComponent = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('Validate Alert Component instance is creating successfully.', () => {
    expect(alertComponent).toBeTruthy();
  });

  it('Validate deleteAlert method.', fakeAsync(() => {
    let injector: Injector;
    let alertStore = new AlertStore(injector);

    const response = {
      body: {
        notifications: [
          { "an alert" },
        ]
      }
    };

    spyOn(alertStore, 'getAlertForAccount').and.returnValue(
      Observable.create((observer: Observer<{ body: any }>) => {
        observer.next(response);
        return observer;
      })
    );

    spyOn(alertStore, 'deleteAlert').and.returnValue(
      Observable.create((observer: Observer<{ body: any }>) => {
        observer.next(response);
        return observer;
      })
    );

    fixture.detectChanges();
    alertComponent.deleteAlert("64239");
  }));

当我运行这个时,我得到这个错误

TypeError: Cannot read property 'get' of undefined
            at <Jasmine>
            at new AlertStore (http://localhost:9876/home//work/components/components/dist/store-manager/fesm2015/store-manager.js:1381:1)
            at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/alerts/alerts.component.spec.ts:377:22)
            at UserContext.<anonymous> (http://localhost:9876/home/work/components/components/node_modules/zone.js/dist/zone-testing.js:1442:1)
            at ZoneDelegate.invoke (http://localhost:9876/home/work/components/components/node_modules/zone.js/dist/zone-evergreen.js:365:1)
            at ProxyZoneSpec.onInvoke (http://localhost:9876/home/work/components/components/node_modules/zone.js/dist/zone-testing.js:305:1)
            at ZoneDelegate.invoke (http://localhost:9876/home/work/components/components/node_modules/zone.js/dist/zone-evergreen.js:364:1)
            at Zone.run (http://localhost:9876/home/work/components/components/node_modules/zone.js/dist/zone-evergreen.js:124:1)
            at runInTestZone (http://localhost:9876/home/work/components/components/node_modules/zone.js/dist/zone-testing.js:554:1)
            at UserContext.<anonymous> (http://localhost:9876/home/work/components/components/node_modules/zone.js/dist/zone-testing.js:569:1)

错误发生在这一行

  let alertStore = new AlertStore(injector);

这是警报存储的样子

import { Injectable, Injector } from '@angular/core';
import { ConfigStore } from './config.store';
import { LoggingService } from 'utils';
import { HttpLibraryService, ResponseType } from '../services/http-library.service';
import { Observable } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class AlertStore extends ConfigStore {
    public readonly ALERT_KEY = "alertDetails";

    private _apiURL: string = null;

    constructor(private injector: Injector) {
        super(injector.get(LoggingService), injector.get(HttpLibraryService));
    }

AlertStore 的构造函数期望它会被 Angular 注入一个 Injector 的实例。为此,Angular 需要创建并了解 AlertStore 的实例。您改为使用 new 关键字创建自己的实例,并传入单元化字段 injector.

我看到您还在测试配置中提供了 MockAlertStore。我猜这就是您真正想要在测试中使用的内容。要从测试配置中检索 MockAlertStore,请使用:

const alertStore = TestBed.get(AlertStore);

它将获取 Angulars TestBed 创建的 MockAlertStore 的实例而不是实际的 AlertStore 来注入(参见:providers: [{ provide: AlertStore, useClass: MockAlertStore },...]) . MockAlertStore class 可能不需要依赖项,但通过这种方式,您还将监视 angular 注入到测试组件中的实例。

Angular 文档中有一个很好的部分是关于 dependency injection 的,这里正在使用它。