core icon indicating copy to clipboard operation
core copied to clipboard

[Testing] [Angular-cli] Can't resolve all parameters when TranslateService is required in injection

Open Supamiu opened this issue 8 years ago • 15 comments

I'm submitting a ... (check one with "x")

[ ] bug report => check the FAQ and search github for a similar issue or PR before submitting
[x] support request => check the FAQ and search github for a similar issue before submitting
[ ] feature request

Current behavior I can't run basic karma+Jasmine tests using angular-cli configuration. I get the following error:

Error: Can't resolve all parameters for I18nToolsService: (?).

And I18nToolsService's constructor is:

constructor(private translator: TranslateService) {
}

My test file is a simple test file :

describe('I18nToolsService', () => {
    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                TranslateModule.forRoot()
            ],
            providers: [
                I18nToolsService
            ]
        });
    });

    it('should be created', inject([I18nToolsService], (service: I18nToolsService) => {
        expect(service).toBeTruthy();
    }));
});

Expected/desired behavior The tests should run fine, with no errors at startup.

Please tell us about your environment:

  • ngx-translate version: 8.0.0

  • Angular version: 4.3.6

  • Karma version: 1.4.1

  • Jasmine version: 2.5.2

  • Angular cli version: 1.4.0

Supamiu avatar Sep 27 '17 08:09 Supamiu

You have to either add the real TranslateService or a mock to the providers key. See: https://angular.io/guide/testing#services-with-dependencies

wilgert avatar Sep 27 '17 11:09 wilgert

Just tried, got the same error with this:

beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                TranslateModule.forRoot()
            ],
            providers: [
                I18nToolsService,
                TranslateService
            ]
        });
    });

Supamiu avatar Sep 27 '17 11:09 Supamiu

Any updates on that? I really need to be able to test my app and at the moment this is the only thing I'm stuck with.

Supamiu avatar Oct 05 '17 13:10 Supamiu

I can not make it work too. I have followed the ionic example testing config for my angular app but it just not work:

import {DebugElement, Injector} from '@angular/core';
import {of} from 'rxjs/observable/of';
import {
  TranslateCompiler,
  TranslateFakeCompiler,
  TranslateLoader,
  TranslateModule,
  TranslateService,
} from '@ngx-translate/core';
import {CommonModule} from '@angular/common';
import {RouterModule} from '@angular/router';
import {ListNavComponent} from './list-nav.component';
import {async, ComponentFixture, getTestBed, TestBed} from '@angular/core/testing';
import {MatListModule, MatIconModule} from '@angular/material';
describe('ListNavComponent', () => {
  let comp: ListNavComponent;
  let fixture: ComponentFixture<ListNavComponent>;
  let de: DebugElement;
  let el: HTMLElement;
  let translate: TranslateService;
  let injector: Injector;

  beforeEach(
    async(() => {
      TestBed.configureTestingModule({
        declarations: [ListNavComponent],
        imports: [
          MatListModule,
          CommonModule,
          RouterModule.forChild([]),
          MatIconModule,
          TranslateModule.forRoot({
            loader: {provide: TranslateLoader, useClass: FakeLoader},
            compiler: {provide: TranslateCompiler, useClass: TranslateFakeCompiler},
          }),
        ],
      }).compileComponents();

      injector = getTestBed();
      translate = injector.get(TranslateService);
      translate.use('en');

      fixture = TestBed.createComponent(ListNavComponent);

      comp = fixture.componentInstance;

      de = fixture.debugElement;
      el = de.nativeElement;
    }),
  );

  it('true is true', () => {
    expect(true).toBe(true);
  });
});

const translations: any = {LOAD: 'This is a test'};

class FakeLoader implements TranslateLoader {
  getTranslation(lang: string) {
    console.log(lang);
    return of(translations);
  }
}

ERROR:

screen shot 2017-12-09 at 14 53 18

sandangel avatar Dec 09 '17 05:12 sandangel

Same here, some input would be nice since testing is an important part of any serious app; please provide some documentation on testing, thanks !

Lakston avatar Dec 18 '17 12:12 Lakston

any updates? Not being able to test the app just because of that is a bommer for my app, please write proper testing documentation if I'm missing anything, even with a TranslateService provided, nothing changed, I tried everything written in the doc.

Supamiu avatar Jan 18 '18 12:01 Supamiu

Are you importing the es7 reflect polyfill? If not, you could try if adding the following line to the polyfills.ts fixes your issues:

import 'core-js/es7/reflect'; // needed for unit testing

and you might also want to check you tsconfig.json file for "emitDecoratorMetadata": true,

jfmaeck avatar Feb 08 '18 09:02 jfmaeck

Has anyone solved this yet? I have been banging my head on the key board for the last few hours.

Albosonic avatar Jun 06 '18 05:06 Albosonic

Have you looked at the example app? https://github.com/ngx-translate/example It includes a spec file that you can use as an example: https://github.com/ngx-translate/example/blob/master/src/app/app.component.spec.ts

ocombe avatar Jun 06 '18 06:06 ocombe

Still issue persist for unit testing parameterized API.

herin0506 avatar Jul 20 '18 07:07 herin0506

Anyone? Having the same problem trying to set up testing with jest + jest-preset-angular.

PowerSupply avatar Mar 15 '19 14:03 PowerSupply

i am facing the same problem anyone have found any solution yet ?

mrsalmanahmad avatar Apr 11 '19 07:04 mrsalmanahmad

I faced the same problem and fixed it this way.

  1. Used this TranslateTestingModule : https://github.com/ngx-translate/core/issues/636#issuecomment-451137902
  2. Modified the contructor of MyComponent (the tested component):
constructor(@Inject(TranslateService) public translate: TranslateService) {
  1. Inside the test file:
beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [
      TranslateTestingModule
    ],
    declarations: [
      MyComponent
    ],
    providers:[
      TranslateService
    ]
  }).compileComponents();
}));

julien-deramond avatar Oct 24 '19 15:10 julien-deramond

I also had the same problem. I managed to solve by putting in tsconfig.spec.json from the root of the project the option emitDecoratorMetada as true.

My tsconfig.spec.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "types": ["jest", "node"],
    "emitDecoratorMetadata": true
  },
  "files": ["src/polyfills.ts"],
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

italoiz avatar Nov 17 '19 20:11 italoiz

@julien-deramond With Angular 9 and Ngx translate 12, the TranslateTestingModule does not seem to be working anymore. The TranslateModule is ignoring the declaration of the mocked pipe. Is anyone else experiencing this issue?

Note: If I turn Angular Ivy off, the module works.

ryboucher avatar Mar 16 '20 20:03 ryboucher