如何在Angular / Jasmine测试中模拟Injector实例?

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

我需要测试使用Injector而非constructor()注入服务的服务。

我使用这种方式的主要原因是大量服务扩展了我的共同SimpleDataService。这里是CompanyServiceProductServiceTagService等,每个人都扩展了SimpleDataService。因此,我不想为super()调用定义多余的参数。

app.module.ts

import { Injector, NgModule } from '@angular/core';

export let InjectorInstance: Injector;

@NgModule({
  // ...
})
export class AppModule {
  constructor(private injector: Injector) {
    InjectorInstance = this.injector;
  }
}

simple-data.service.ts

import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { InjectorInstance } from 'src/app/app.module';
import { PaginateInterface } from 'src/app/models/paginate/paginate.interface';
import { environment } from 'src/environments/environment';

export class SimpleDataService<T> {
  public url = environment.apiUrl;
  private http: HttpClient;
  public options: any;
  public type: new () => T;

  constructor(
    private model: T,
  ) {
    this.http = InjectorInstance.get<HttpClient>(HttpClient);
  }

  getAll(): Observable<PaginateInterface> {
    return this.http.get(this.url + this.model.api_endpoint, this.options)
      .pipe(map((result: any) => result));
  }
}

simple-data.service.spec.ts

import { HttpClient } from '@angular/common/http';
import { TestBed } from '@angular/core/testing';
import { BrowserDynamicTestingModule,
  platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import { Tag } from 'src/app/models/tag/tag.model';
import { SimpleDataService } from './simple-data.service';

describe('SimpleDataService', () => {
  TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());

  const model = new Tag();
  const simpleDataService = new SimpleDataService(model);
});

现在我收到TypeError: Object prototype may only be an Object or null: undefined错误消息。发生这种情况的原因是此行:

this.http = InjectorInstance.get<HttpClient>(HttpClient);

InjectorInstance是这里的undefined

如何避免这种方式将Injector实例模拟到我的InjectorInstance属性中?:

  constructor(
    private model: T,
    private injectorInstance: Injector,
  ) { }
angular mocking jasmine karma-jasmine testbed
1个回答
0
投票

部分问题是您正在使用export let声明InjectorInstance。这种类型的声明使修改任何其他文件(例如:测试文件)中的字段成为非法。一种更改方法是使InjectorInstance成为AppModule类的静态字段,如:

export class AppModule {
  static InjectorInstance: Injector;
  (...)
}

然后您可以在该字段中使用TestBed,因为Injector的接口实际上非常简单,仅包含get方法。如:

beforeEach(async(() => {
  TestBed.configureTestingModule({(...)});
}));

beforeEach(() => {
  AppModule.InjectorInstance = TestBed;
});

是否将依赖项注入模式交换为服务定位器模式是一个好主意,这是一个完全不同的讨论。

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