ngx-translate / core

The internationalization (i18n) library for Angular
MIT License
4.51k stars 576 forks source link

How to spyOn a custom translation loader's getTranslation method? #488

Closed kamok closed 6 years ago

kamok commented 7 years ago

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'm using a custom loader which TranslationLoaderService implements TranslateLoader. In my real getTranslation() method, I make a call to my storage service for a JSON with my translation, as such.

getTranslation(locale: string): Observable<any> {
    return new Observable((observer) => {
      this.storage.get('translations').then((data: Object[]) => {
        const translationData = data.filter((translations: Object) => {
                                  return translations['locale'] == locale;
                                })[0]['translations'];
        observer.next(translationData);
        observer.complete();
      });
    })
  }

The problem with mocking the storage class and returning a Promise.resolve({}) is that it is async. So instead of doing that, I'm mocking the entire return of the getTranslation() method with Jasmine's spyOn.

I expected this to work: spyOn(TranslationLoaderService,"getTranslation").and.returnValue(Observable.of({HELLO: "there"})); but it's giving me this weird error:

(39,37): error TS2345: Argument of type '"getTranslation"' is not assignable to parameter of type '"prototype"'.
webpack: Failed to compile.

And subsequently: Error: <spyOn> : getTranslation() method does not exist.

I'm using the latest version of ng2-translate and Ionic framework.

kamok commented 7 years ago

I managed to mock the storage class that makes async call. I use the Jasmine done and setTimeOut to let the storage mock data load which effectively works. Though, still haven't figured out how to mock the getTranslation method. I'll leave this thread open in case someone needs to do this, though any other ways to load translations such as using HTTP will be easily mockable if they just mock the method call for the service.

shairez commented 7 years ago

Thanks @kamok

I think it's best to add this to the repo Wiki and close this issue.

@ocombe WDYT ?

ocombe commented 7 years ago

Sure, any doc is always good!

ocombe commented 6 years ago

Hello, I'm closing this issue because it's too old. If you have a similar problem with recent version of the library, please open a new issue.

You can find an example of unit test (including a spyOn) in https://github.com/ngx-translate/example/blob/master/src/app/app.component.spec.ts