Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

unit testing with ng2-translate #235

Closed
agustincassanioe opened this issue Sep 14, 2016 · 7 comments
Closed

unit testing with ng2-translate #235

agustincassanioe opened this issue Sep 14, 2016 · 7 comments

Comments

@agustincassanioe
Copy link

agustincassanioe commented Sep 14, 2016

Hi there,

I have the following unit test body:

import { async, TestBed } from '@angular/core/testing';
import { Http } from '@angular/http';
import { ViewContainerRef } from "@angular/core";

import { AppComponent } from './app.component';
import { TranslateModule, TranslateLoader, TranslateService, TranslateStaticLoader } from 'ng2-translate/ng2-translate';

describe('lp3-ui', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [TranslateModule.forRoot({
        provide: TranslateLoader,
        useFactory: (http: Http) => new TranslateStaticLoader(http, 'assets/i18n', '.json'),
        deps: [Http]
      })],
      providers: [TranslateService]
    });
  });

  it('should create the app', async(() => {
    let fixture = TestBed.createComponent(AppComponent);
    let app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
});

When I run unit test with "npm test" I am getting the following error stack:

PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 0 of 2 SUCCESS (0 secs / 0 secs)
14 09 2016 19:27:11.022:DEBUG [phantomjs.launcher]: AppComponent activated

14 09 2016 19:27:11.023:DEBUG [phantomjs.launcher]: No stored language!
Browser detected language is en

14 09 2016 19:27:11.023:DEBUG [phantomjs.launcher]: Setting language to: en

14 09 2016 19:27:11.026:DEBUG [middleware:source-files]: Requesting /client/assets/i18n/en.json /
14 09 2016 19:27:11.026:DEBUG [middleware:source-files]: Fetching /client/assets/i18n/en.json
DEBUG: 'AppComponent activated'
DEBUG: 'No stored language!'
DEBUG: 'Browser detected language is', 'en'
DEBUG: 'Setting language to:', 'en'
PhantomJS 2.1.1 (Mac OS X 0.0.0) lp3-ui should create the app FAILED
    Failed: Response with status: 404 Not Found for URL: null
    webpack:///~/@angular/core/testing/async.js:37:0 <- config/karma-test-shim.js:13758:31
    onHandleError@webpack:///~/zone.js/dist/async-test.js:40:0 <- config/karma-test-shim.js:12887:36
    handleError@webpack:///~/zone.js/dist/zone.js:196:0 <- config/karma-test-shim.js:11594:53
    onHandleError@webpack:///~/zone.js/dist/long-stack-trace-zone.js:106:0 <- config/karma-test-shim.js:12816:51
    handleError@webpack:///~/zone.js/dist/zone.js:196:0 <- config/karma-test-shim.js:11594:53
    onHandleError@webpack:///~/@angular/core/src/zone/ng_zone_impl.js:73:0 <- config/karma-test-shim.js:26685:42
    handleError@webpack:///~/zone.js/dist/zone.js:196:0 <- config/karma-test-shim.js:11594:53
    runTask@webpack:///~/zone.js/dist/zone.js:128:0 <- config/karma-test-shim.js:11526:56
    invoke@webpack:///~/zone.js/dist/zone.js:293:0 <- config/karma-test-shim.js:11691:41
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 2 of 2 (1 FAILED) (0.245 secs / 0.077 secs)
14 09 2016 19:27:11.218:DEBUG [karma]: Run complete, exiting.
PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR
  Response with status: 404 Not Found for URL: null
  at webpack:///~/ng2-translate/src/translate.service.js:135:0 <- config/karma-test-shim.js:47459
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 2 of 2 (1 FAILED) ERROR (0.262 secs / 0.077 secs)
14 09 2016 19:27:11.233:DEBUG [karma]: Run complete, exiting.
14 09 2016 19:27:11.234:DEBUG [launcher]: Disconnecting all browsers
14 09 2016 19:27:11.237:DEBUG [launcher]: Process PhantomJS exited with code 0
14 09 2016 19:27:11.238:DEBUG [temp-dir]: Cleaning temp dir /var/folders/js/t6tqk50n3895hy3gf_sqkx2r0000gn/T/karma-29842367
14 09 2016 19:27:11.241:DEBUG [launcher]: Finished all browsers
npm ERR! Test failed.  See above for more details.

I am working with ng2-translate version 2.4.3 and Angular 2 RC5.

Thanks in advance for your help!

@agustincassanioe
Copy link
Author

agustincassanioe commented Sep 14, 2016

Sorry, I did not mention when is failing. This is the body of my AppComponent:

import { Component, ViewContainerRef } from '@angular/core';

import { TranslateService } from 'ng2-translate/ng2-translate';

import { DEFAULT_LANGUAGE, LANGUAGE_STORAGE_KEY, isSupportedLanguage } from './common';

@Component({
  selector: 'lp3-app',
  styles: [require('./app.component.scss')],
  template: require('./app.component.html')
})
export class AppComponent {
  constructor(private translate: TranslateService, private viewContainerRef: ViewContainerRef) {
    console.debug('AppComponent activated');

var userLang = localStorage.getItem(LANGUAGE_STORAGE_KEY);

if (userLang) {
  console.debug('Restoring language from localStorage');
} else {
  console.debug('No stored language!');
  userLang = navigator.language.split('-')[0]; // use navigator lang if available
  console.debug('Browser detected language is', userLang);
}

userLang = isSupportedLanguage(userLang) ? userLang : DEFAULT_LANGUAGE;
console.debug('Setting language to:', userLang);
this.translate.use(userLang).toPromise().then(() => {
  console.debug('AppComponent language set to:', this.translate.currentLang);
});
localStorage.setItem(LANGUAGE_STORAGE_KEY, userLang);
  }
}

I have tried commented it out entirely and uncommented it out section by section. The part that is throwing the error is the following one:

this.translate.use(userLang).toPromise().then(() => {
  console.debug('AppComponent language set to:', this.translate.currentLang);
});

The resto of the code works perfectly.

Thanks!

@ghost
Copy link

ghost commented Dec 3, 2016

Hi,
I am running similar test as above with ng2-translate service
When running the tests, I am getting the following error:

AppComponent should create the app FAILED
Failed: Can't resolve all parameters for AppComponent

Please find attached code samples and test error report.
ng2-translate-unit-testing-error.txt
app.component.spec.ts.txt
app.component.ts.txt

ng-translate version:4.0.1
Angular 2 version:2.2.0

Can you please provide some documentation and code samples on how to run unit tests with ng2-translate?
Your help would be appreciated
Thanks.

@ocombe
Copy link
Member

ocombe commented Dec 21, 2016

@agustincassanioe sorry for not answering to this message earlier.
The problem is that karma serves all files from the folder "/base", so you probably have to change this:

useFactory: (http: Http) => new TranslateStaticLoader(http, 'assets/i18n', '.json'),

to this

useFactory: (http: Http) => new TranslateStaticLoader(http, 'base/assets/i18n', '.json'),

@vikram-kerkar your problem is probably that you don't have to provide the translate service, try to remove this line: providers: [TranslateService ]. The TranslateModule.forRoot method already provides the TranslateService provider

@ocombe
Copy link
Member

ocombe commented Dec 21, 2016

Closing this for now, let me know if it's not working, I'll reopen.

@ocombe ocombe closed this as completed Dec 21, 2016
@ghost
Copy link

ghost commented Dec 30, 2016

I removed the translate service dependency from AppComponent and injected it into the App Module instead. This has fixed the issue. For components that use the translate pipe, I followed your setup from translate.pipe.spec.ts and everything is working fine now.
Thanks 👍

@qiluo
Copy link

qiluo commented Apr 11, 2017

hi @ocombe , I followed your guide, my testing setup looks like

function translateLoader(http: Http) {
  return new TranslateStaticLoader(http, 'base/assets/i18n', '.json');
}

describe('MyApp Component', () => {
  let fixture;
  let component;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyApp],
      imports: [
        HttpModule,
        IonicModule.forRoot(MyApp),
        TranslateModule.forRoot({
          provide: TranslateLoader,
          useFactory: (translateLoader),
          deps: [Http]
        })
      ],
      providers: [
        StatusBar,
        SplashScreen
      ]
    })
  }));

but I still got error

11 04 2017 16:39:57.325:INFO [PhantomJS 2.1.1 (Mac OS X 0.0.0)]: Connected on socket Q-ACsrb7Xki-GphLAAAA with id 42310708
11 04 2017 16:39:58.680:WARN [web-server]: 404: /base/assets/i18n/zh.json
11 04 2017 16:39:58.749:ERROR [launcher]: PhantomJS crashed.

I'm on ng2-translate@5.0.0

@boradakash
Copy link

Hi @qiluo
did you resolve this 404 /base/assets/i18n/zh.json issue?
If yes,
Your help would be appreciated
Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants