首页 > 解决方案 > Angular 8 测试时无法获取 Injector

问题描述

我在这里在stackblitz中创建了一个示例项目。示例项目有 2 个组件(TestComponent 和 Test1Component)、1 个服务(TestService)和 1 个 TestComponent 将扩展的类(Base)。

有一个用例我需要在不使用构造函数的情况下获取服务实例,我正在使用下面的代码并且它工作正常。

应用模块:

@NgModule({
  imports:      [ BrowserModule, FormsModule,],
  declarations: [ AppComponent,  TestComponent, Test1Component ],
  bootstrap:    [ AppComponent ],
  exports: [TestComponent, Test1Component]
})
export class AppModule {
  static injector: Injector;
  constructor(injector: Injector) {
    AppModule.injector = injector;
  }
}

然后在 Base.ts 中。

export class Base {
  constructor() {
    console.log("i am base");
    let service = AppModule.injector.get(TestService); // with this i can get test service succesfully
  }
}

当我尝试为 TestComponent 编写测试用例时,抛出错误,请参见下面的代码,我不知道为什么会发生这种情况,请帮助...谢谢。

describe("TestComponent", () => {
  // throws error, Error during loading: Uncaught ReferenceError: Cannot access 'TestComponent' before initialization
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [AppModule]
    }).compileComponents();
    fixture = TestBed.createComponent(TestComponent); 
    component = fixture.componentInstance;
    fixture.detectChanges();
  }));

  it("should create", () => {
    expect(component).toBeTruthy();
  });
});

我的环境:

Angular CLI: 8.3.14
Node: 10.16.0
OS: darwin x64
Angular: 8.2.12
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.803.14
@angular-devkit/build-angular     0.803.14
@angular-devkit/build-optimizer   0.803.14
@angular-devkit/build-webpack     0.803.14
@angular-devkit/core              8.3.14
@angular-devkit/schematics        8.3.14
@angular/cdk                      8.2.3
@angular/cli                      8.3.14
@angular/material                 8.2.3
@ngtools/webpack                  8.3.14
@schematics/angular               8.3.14
@schematics/update                0.803.14
rxjs                              6.4.0
typescript                        3.5.3
webpack                           4.39.2

标签: angularangular8angular-test

解决方案


  • 更新karma.config.jsAngular-cli用作

    module.exports = function (config) {
        config.set({
        basePath: '',
         frameworks: ['jasmine', '@angular/cli'],
         plugins: [
         require('karma-jasmine'),
         require('karma-chrome-launcher'),
         require('karma-jasmine-html-reporter'),
         require('karma-coverage-istanbul-reporter'),
         require('@angular/cli/plugins/karma')
       ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'dev'
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
    

    }); };

Server Runnerport 9876上收听

  • 然后使用中的 types 选项自动导入类型tsconfig.json

"types": ["jasmine"],

  • 在里面test.service.ts它必须包含 Specs 导入

所以要使示例有效,只需更新test.service.ts并使其包含以下行:

import './test/test.component.spec';

对于运行测试,您应该使用测试运行器,Karma而不是Node因为它不了解您的测试框架


推荐阅读