运行此代码时出错:
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();
}
}
答案 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);