测试 - 没有 TranslateService 的提供者 [英] test - No provider for TranslateService

查看:30
本文介绍了测试 - 没有 TranslateService 的提供者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ng test 命令运行一些测试,但收到以下错误消息:

I'm running some tests using the ng test command and I get the following error message:

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 模块:

I also tried importing the BrowserModule module:

imports: [
  BrowserAnimationsModule,

我尝试添加一个 TranslateService 提供程序:

And I tried adding a TranslateService provider:

providers: [
  TranslateService
]

我终于尝试将两个服务的两个成员变量注入到组件构造函数中:

I finally tried having two member variables for the two services to be injected into the component constructor:

let translateService: TranslateService;
let screenDeviceService: ScreenDeviceService;

并提供它们:

providers: [
  TranslateService,
  ScreenDeviceService
]

并得到它们:

translateService = TestBed.get(TranslateService);
screenDeviceService = TestBed.get(ScreenDeviceService);

但没有任何帮助.

我使用的是 Angular 9.0.4

I'm under Angular 9.0.4

更新:我最终使用了真正的翻译服务而不是模拟的翻译服务,并且不得不杀死测试运行程序并再次输入 ng test 命令以考虑我的源代码.>

UPDATE: I ended up using the real translate service instead of the mocked one and had to kill the test runner and type in again the ng test command for my source code to be considered.

推荐答案

在你的测试 spec.ts 文件中,你可以添加这种类型的导入,使用 forRoot():

In your test spec.ts file you could add this type of import, with forRoot():

TranslateModule.forRoot()

示例:

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        TranslateModule.forRoot(),
        HttpClientTestingModule
      ],
      declarations: [ HomeComponent ],
      schemas: [ NO_ERRORS_SCHEMA ]
    })
    .compileComponents();
  }));

这是因为您还没有测试 TranslateModule.这个解决方案对我有用.

This because you haven't to test the TranslateModule too. This solution works to me.

这篇关于测试 - 没有 TranslateService 的提供者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆