【问题标题】:enviromentService is undefined when calling fixture.detectChanges?调用fixture.detectChanges时未定义环境服务?
【发布时间】:2017-11-06 14:59:14
【问题描述】:

运行此代码时出现错误:

   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();
  }
}

【问题讨论】:

  • EnvironmenService 的模拟在哪里?如果您不使用一个,那么为什么要添加一个 useValue(顺便说一句,它是 useValue 而不是 userValue)?

标签: javascript angular jasmine karma-runner


【解决方案1】:

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

{ provide: EnvironmentService, userValue: EnvironmentService }

如果EnvironmentService 是类型,请尝试将userValue 更改为useClass,如果是值,请尝试将useValue

【讨论】:

  • 它不起作用,我们已经更改了它但不幸的是它不起作用。
  • @masterach 我的回答有错字。试试useClass,而不是userClass
  • 这有帮助,现在等待一秒钟进行完整的实施
【解决方案2】:

同意@BeetleJuice 提供的解决方案。至于您遇到的错误: 类型错误:this.enviromentService 未定义 这是因为您需要按以下方式完成作业

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

【讨论】:

  • 这没有帮助
猜你喜欢
  • 2022-12-05
  • 2018-08-09
  • 2018-03-03
  • 2017-12-12
  • 1970-01-01
  • 1970-01-01
  • 2020-01-03
  • 2020-03-27
  • 1970-01-01
相关资源
最近更新 更多