获取类型错误。当使用注入器运行karma测试时,无法读取undefine的'get'属性。

问题描述 投票:0回答:1

所以在我的一个Karma测试中,看起来像下面,它显示TypeError: Cannot read property '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));
    }
angular karma-jasmine karma-runner
1个回答
1
投票

的构造函数 AlertStore 期待它将被注入一个实例的 Injector 的实例。为了做到这一点,Angular需要创建并意识到该实例的 AlertStore. 你可以使用 new 关键字,传入单位化字段。injector.

我看到你还提供了一个 MockAlertStore 在你的测试配置中。我猜想这就是你真正想在测试中使用的东西。要检索 MockAlertStore 从测试配置中使用。

const alertStore = TestBed.get(AlertStore);

它将获得 MockAlertStore 由Angulars创建 TestBed 拟注入而不是实际注入 AlertStore (见。providers: [{ provide: AlertStore, useClass: MockAlertStore },...]). 该 MockAlertStore 类可能不需要依赖,但这样一来,你也会窥探到angular注入到测试组件中的实例。

Angular文档中有很好的章节介绍了 依赖注入 这里用的是。

© www.soinside.com 2019 - 2024. All rights reserved.