我正在使用
但是没有什么帮助。 我使用的是 Angular
ng test
命令运行一些测试,但是我收到了以下错误消息:NullInjectorError: R3InjectorError(DynamicTestModule)[TranslateService -> TranslateService]:
NullInjectorError: No provider for TranslateService!
测试内容为:
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { TranslateTestingModule } from 'ngx-translate-testing';
import { CoreModule } from './core.module';
const ENGLISH_LANGUAGE = 'en';
describe('AppComponent', () => {
let fixture: ComponentFixture<AppComponent>;
let appComponent: AppComponent;
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
appComponent = fixture.componentInstance;
});
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
imports: [
CoreModule,
TranslateTestingModule
.withTranslations(ENGLISH_LANGUAGE, require('assets/i18n/en.json'))
.withDefaultLanguage(ENGLISH_LANGUAGE)
],
}).compileComponents();
});
it('should create the app', async(() => {
expect(appComponent).toBeTruthy();
}));
it('should have as title', async(() => {
appComponent.ngOnInit();
fixture.whenStable().then(() => {
expect(appComponent.testTitle).toEqual('app');
})
}));
});
组件是:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
testTitle?: string;
constructor(
private translateService: TranslateService,
private screenDeviceService: ScreenDeviceService
) {}
public ngOnInit() {
const subscription: Subscription = this.translateService.get('app.title').subscribe((text: string) => {
this.afterLanguageResourcesLoaded();
subscription.unsubscribe();
});
}
private afterLanguageResourcesLoaded(): void {
this.setAppMetaData();
}
private setAppMetaData(): void {
this.screenDeviceService.setMetaData({
title: this.translateService.instant('app.title'),
description: this.translateService.instant('app.description')
});
this.testTitle = this.translateService.instant('app.title');
}
}
我也尝试导入BrowserModule
模块:
imports: [
BrowserAnimationsModule,
我尝试添加了一个TranslateService
提供者:
providers: [
TranslateService
]
我最终尝试在组件构造函数中设置两个成员变量,用于注入这两个服务:
let translateService: TranslateService;
let screenDeviceService: ScreenDeviceService;
并提供给他们:
providers: [
TranslateService,
ScreenDeviceService
]
获取它们:
translateService = TestBed.get(TranslateService);
screenDeviceService = TestBed.get(ScreenDeviceService);
但是没有什么帮助。 我使用的是 Angular
9.0.4
版本。
更新:最终我使用了真正的翻译服务,而不是模拟的服务,并且不得不终止测试运行程序并重新输入 ng test
命令,以便我的源代码得到考虑。
TranslateService
没有在 Angular 上下文中创建,因此无法被注入或者被找到。 - Stephane