调用fixture.detectChanges时,enviromentService是未定义的?

时间:2017-11-06 14:59:14

标签: javascript angular jasmine karma-runner

运行此代码时出错:

   beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ SharedTestingModule,
        TranslateModule.forRoot({
          loader: { provide: TranslateLoader, useValue: mockTranslateLoader }
        })],
      declarations: [ RequestInfoComponent, StaticContentComponent ],
      providers: [{ provide: EnvironmentService, userValue: EnvironmentService }]
    })
      .compileComponents();
  }));
  beforeEach(() => {
    fixture = TestBed.createComponent(RequestInfoComponent);
    component = fixture.componentInstance;
    componentHtml = fixture.debugElement.nativeElement;
    environmentService = fixture.debugElement.injector.get(EnvironmentService);
  });

问题是fixture.detectChanges()。如果我删除fixture.detectChanges()然后一切正常,但我应该用它运行代码。我无法删除它。

错误是:

  

TypeError:this.enviromentService未定义

这是我在组件中的代码:

import { Component, OnInit } from '@angular/core';
import { EnvironmentService } from 'app/shared/environment.service';
@Component({
  selector: 'app-request-info',
  templateUrl: './request-info.component.html',
  styles: []
})
export class RequestInfoComponent implements OnInit {
  urlPrefix: string;
  constructor(private environmentService: EnvironmentService) { }
  ngOnInit() {
    this.urlPrefix = this.environmentService.getWebContentUrlPrefix();
  }
}

2 个答案:

答案 0 :(得分:1)

在第一个beforeEach区块中,您拥有的第一个提供商有一个类型:

{ provide: EnvironmentService, userValue: EnvironmentService }

如果userValue是某种类型,请尝试将useClass更改为EnvironmentService;如果是值,则尝试将useValue更改为<{1}}。

答案 1 :(得分:-1)

同意@BeetleJuice提供的解决方案。至于您的错误: TypeError:this.enviromentService未定义 这是因为您需要按照以下方式进行分配

component.environmentService = fixture.debugElement.injector.get(EnvironmentService);