GithubHelp home page GithubHelp logo

mwootendev / ngx-translate-plugins Goto Github PK

View Code? Open in Web Editor NEW
15.0 15.0 10.0 2.91 MB

Utilities plugins for the @ngx-translate translation library.

License: MIT License

JavaScript 7.84% TypeScript 87.49% HTML 2.55% CSS 0.19% Dockerfile 1.93%

ngx-translate-plugins's People

Contributors

7jpsan avatar andyhammar avatar carlosgomes-co avatar dependabot[bot] avatar fvilers avatar mwootendev avatar paul-kr avatar sjarmero avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

ngx-translate-plugins's Issues

Add Angular 11 support

Describe the bug
During install in an Angular 11 project it reports:

npm WARN [email protected] requires a peer of @angular/common@^10.0.0-rc.0 || >=10.0.0 <11.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN [email protected] requires a peer of @angular/core@^10.0.0-rc.0 || >=10.0.0 <11.0.0 but none is installed. You must install peer dependencies yourself.

Please publish an Ivy distribution

Hi @mwootendev, thanks for the helpful library, I have just started helping a client migrate to Angular 13 and this package is proving to be the sticking point. They use jest (like the reporters of your two existing issues do) and I believe all of the issues can be solved by publishing an Ivy distribution per the latest guidance, full info below.


Describe the bug

I believe both of the open issues #48 and #49 are symptoms of the same point - the absence of an Ivy distribution of this library for use with Angular 13+ is problematic.

If you attempt to use this library with jest you will run into #49 if you do not run ngcc properly, and then #48 once you do.

I see you currently have "enableIvy": false - is there a particular reason for this?

One of the key parts of the guide for publishing Angular libraries (https://angular.io/guide/creating-libraries) is:

If you intend to publish your library to npm, compile with partial-Ivy code by setting "compilationMode": "partial" in tsconfig.prod.json.

The compilationMode option should replace the enableIvy one entirely AFAIK.

All users currently see this when using the library as a result of the above:

image

Reproduction

If you want to trivially reproduce the two issues above you can create an Nx workspace with the Angular preset (because it wires up a working jest + Angular setup out of the box):

npx create-nx-workspace --preset=angular

E.g.

image

And then install:

npm i ngx-translate-testing @ngx-translate/core @ngx-translate/http-loader

And update app.component.ts

image

At this stage you will be able to reproduce #49 by running the tests (assuming ngcc hasn't yet run)

Then run:

npm run postinstall

...to trigger ngcc

At this stage you will be able to reproduce #48 by running the tests

Compile Error with Angular 10

When running ng test after updating to Angular 10:

ERROR in node_modules/ngx-translate-testing/lib/testing.module.d.ts:13:56 - error TS2314: Generic type 'ModuleWithProviders<T>' requires 1 type argument(s).

13 export declare class TranslateTestingModule implements ModuleWithProviders {

Function calls are not supported in decorators but 'TranslateTestingModule' was called.

Hey,

I am trying to use your TranslateTestingModule in one of my modules TranslationTestHelperModule:

declare var require: any
const TRANSLATIONS_EN = require('../../assets/i18n/en.json');
const TRANSLATIONS_DE = require('../../assets/i18n/de.json');

@NgModule({
  imports: [
    HttpClientTestingModule,
    TranslateTestingModule
      .withTranslations('de', TRANSLATIONS_DE)
      .withTranslations('en', TRANSLATIONS_EN)
      .withDefaultLanguage('de')
  ]
})
export class TranslationTestHelperModule { }

For running the tests it works great, but when I tried to build the project it throws an error:

ERROR in Error during template compile of 'TranslationTestHelperModule'
  Function calls are not supported in decorators but 'TranslateTestingModule' was called.

My TranslationTestHelperModule is used just in the .spec.ts files.

My dependencies:

"@angular/core": "^10.1.3"
"@ngx-translate/core": "^13.0.0"

dev dependencies:
"ngx-translate-testing": "^5.0.0"

Any idea how to make the build running?

Thank you.

Not working with Angular 12 Jest

Class constructor TranslateLoader cannot be invoked without 'new' --- error is showing while running jest test in angular 12, please someone help me.

"devDependencies": {
"@angular-devkit/build-angular": "~12.0.0",
"@angular/cli": "~12.0.0",
"@angular/compiler-cli": "~12.0.0",
"@fullhuman/postcss-purgecss": "^5.0.0",
"@types/jest": "^29.2.0",
"@types/node": "^12.11.1",
"cssnano": "^5.1.13",
"jest": "^29.2.1",
"jest-preset-angular": "^12.2.2",
"jscat": "0.0.2",
"ngx-translate-testing": "^5.2.0",
"postcss": "^8.4.17",
"postcss-loader": "^7.0.1",
"postcss-preset-env": "^7.8.2",
"postcss-scss": "^4.0.5",
"sass": "^1.55.0",
"typescript": "~4.2.3"
}

Error log:

TypeError: Class constructor TranslateLoader cannot be invoked without 'new'

  at new TestTranslateLoader (projects/testing/src/lib/test-translate-loader.service.ts:23:5)
  at TranslateTestingModule.get (projects/testing/src/lib/testing.module.ts:95:7)
  at R3Injector.Object.<anonymous>.R3Injector.processInjectorType (../packages/core/src/di/r3_injector.ts:366:61)
  at ../packages/core/src/di/r3_injector.ts:326:20
  at ../packages/core/src/util/array_utils.ts:71:74
      at Array.forEach (<anonymous>)
  at deepForEach (../packages/core/src/util/array_utils.ts:71:9)
  at ../packages/core/src/util/array_utils.ts:71:49
      at Array.forEach (<anonymous>)
  at deepForEach (../packages/core/src/util/array_utils.ts:71:9)
  at ../packages/core/src/util/array_utils.ts:71:49
      at Array.forEach (<anonymous>)
  at deepForEach (../packages/core/src/util/array_utils.ts:71:9)
  at R3Injector.Object.<anonymous>.R3Injector.processInjectorType (../packages/core/src/di/r3_injector.ts:325:9)
  at ../packages/core/src/di/r3_injector.ts:147:44
  at ../packages/core/src/util/array_utils.ts:71:74
      at Array.forEach (<anonymous>)
  at deepForEach (../packages/core/src/util/array_utils.ts:71:9)
  at new R3Injector (../packages/core/src/di/r3_injector.ts:147:5)
  at createInjectorWithoutInjectorInstances (../packages/core/src/di/r3_injector.ts:97:10)
  at new NgModuleRef$1 (../packages/core/src/render3/ng_module_ref.ts:54:24)
  at R3TestBedCompiler.Object.<anonymous>.R3TestBedCompiler.finalize (../packages/core/testing/src/r3_test_bed_compiler.ts:260:26)
  at TestBedRender3.get (../packages/core/testing/src/r3_test_bed.ts:370:43)
  at TestBedRender3.Object.<anonymous>.TestBedRender3.inject (../packages/core/testing/src/r3_test_bed.ts:268:25)
  at TestBedRender3.Object.<anonymous>.TestBedRender3.createComponent (../packages/core/testing/src/r3_test_bed.ts:325:40)
  at Function.Object.<anonymous>.TestBedRender3.createComponent (../packages/core/testing/src/r3_test_bed.ts:177:33)
  at src/app/shared/components/translate/translate.component.spec.ts:23:23
  at _ZoneDelegate.Object.<anonymous>._ZoneDelegate.invoke (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:409:30)
  at ProxyZoneSpec.Object.<anonymous>.ProxyZoneSpec.onInvoke (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:3830:43)
  at _ZoneDelegate.Object.<anonymous>._ZoneDelegate.invoke (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:408:56)
  at Zone.Object.<anonymous>.Zone.run (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:169:47)
  at Object.wrappedFunc (node_modules/zone.js/bundles/zone-testing-bundle.umd.js:4330:34)

Tests are not working

Describe the bug
I have just cloned the repo and I've tried to run the tests and they're not working. Nor the app, nor the lib tests.

To Reproduce
Steps to reproduce the behavior:

  1. Clone the repo
  2. Install the dependencies with npm install
  3. Run npm run test:appor npm run test:lib
  4. See the errors in the terminal

Expected behavior
Tests running successfully.

Desktop (please complete the following information):

  • OS: Ubuntu 20.04
  • Browser N/A
  • Version N/A

Additional context
This is the full log of each command.

npm run test:app

 ~/dev/ngx-translate-plugins   develop ±  npm run test:app

> [email protected] test:app
> ng test --project=ngx-translate-plugins

⠙ Generating browser application bundles (phase: building)...20 09 2021 13:17:06.245:WARN [karma]: No captured browser, open http://localhost:9876/
20 09 2021 13:17:06.258:INFO [karma-server]: Karma v5.2.3 server started at http://localhost:9876/
20 09 2021 13:17:06.259:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
20 09 2021 13:17:06.261:INFO [launcher]: Starting browser Chrome
✔ Browser application bundle generation complete.

./src/app/app.component.spec.ts:3:0-63 - Error: Module not found: Error: Can't resolve 'ngx-translate-testing' in '/home/dhalcojor/dev/ngx-translate-plugins/src/app'

Error: src/app/app.component.spec.ts:5:40 - error TS2307: Cannot find module 'ngx-translate-testing' or its corresponding type declarations.

5 import { TranslateTestingModule } from 'ngx-translate-testing';
                                         ~~~~~~~~~~~~~~~~~~~~~~~



20 09 2021 13:17:10.842:INFO [Chrome 93.0.4577.82 (Linux x86_64)]: Connected on socket UD4TUSBejzJh8mqNAAAA with id 81355842
20 09 2021 13:17:10.896:WARN [web-server]: 404: /_karma_webpack_/main.js
Chrome 93.0.4577.82 (Linux x86_64): Executed 0 of 0 SUCCESS (0.001 secs / 0 secs)
TOTAL: 0 SUCCESS
TOTAL: 0 SUCCESS

npm run test:lib

 ~/dev/ngx-translate-plugins   develop ±  npm run test:lib

> [email protected] test:lib
> ng test --project=testing

⠙ Generating browser application bundles (phase: building)...20 09 2021 13:21:57.666:WARN [karma]: No captured browser, open http://localhost:9876/
20 09 2021 13:21:57.680:INFO [karma-server]: Karma v5.2.3 server started at http://localhost:9876/
20 09 2021 13:21:57.680:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
20 09 2021 13:21:57.684:INFO [launcher]: Starting browser Chrome
✔ Browser application bundle generation complete.

./projects/testing/src/test.ts:2:0-29 - Error: Module not found: Error: Can't resolve 'core-js/es7/reflect' in '/home/dhalcojor/dev/ngx-translate-plugins/projects/testing/src'


20 09 2021 13:22:01.815:INFO [Chrome 93.0.4577.82 (Linux x86_64)]: Connected on socket C-QCDt6QKhPBHHKzAAAA with id 23557703
20 09 2021 13:22:01.868:WARN [web-server]: 404: /_karma_webpack_/main.js
Chrome 93.0.4577.82 (Linux x86_64): Executed 0 of 0 SUCCESS (0.02 secs / 0 secs)
TOTAL: 0 SUCCESS
TOTAL: 0 SUCCESS

Upgrade ngx-translate/core and angular peerDependencies

After upgrade to Angular 7 and ngx-translate/core 11 the following error is displaying when using the last version of the package:
npm WARN [email protected] requires a peer of @angular/common@^6.0.0-rc.0 || ^6.0.0 but none is installed. You must install peer dependencies yourself. npm WARN [email protected] requires a peer of @angular/core@^6.0.0-rc.0 || ^6.0.0 but none is installed. You must install peer dependencies yourself. npm WARN [email protected] requires a peer of @ngx-translate/core@^10.0.0 but none is installed. You must install peer dependencies yourself.

I think peerDependencies must be update to:
"@angular/common": "^7.0.0-rc.0 || ^7.0.0", "@angular/core": "^7.0.0-rc.0 || ^7.0.0", "@ngx-translate/core": "^11.0.0",

Use TranslateTestingModule in a SharedModule

it would be great to give an example of how to use TranslateTestingModule inside a SharedTestModule and use it in a feature module.
I did something like this but didn't work out.

import {NgModule} from '@angular/core';
import {TranslateTestingModule} from 'ngx-translate-testing';

@NgModule({
  imports: [
    TranslateTestingModule
      .withTranslations('en', require('../src/assets/i18n/en.json'))
      .withTranslations('de', require('../src/assets/i18n/de.json'))
      .withDefaultLanguage('en')
  ]
})
export class SharedTestModule { }

Thanks in Advance :)

Problems with RxJS 7

Is your feature request related to a problem? Please describe.
The whole angular universe didn't integrate the new version of rxjs (7.x) yet, even in version 14.

There are known issues with angular material that component events are being fired when they are not supposed to be fired with rxjs 7.x and not with 6.x.

ReactiveX/rxjs#6978

Describe the solution you'd like
Downgrade rxjs to 6.x until 7.x is fully supported

Describe alternatives you've considered
No other alternatives.

Additional context
None

Support custom translate parser

Is your feature request related to a problem? Please describe.
I developed a new parser for the TranslateService, but I can't integrate it with unit testing using TranslateTestingModule.
A lot of my tests use it for easy language support. It'll be very helpful if this library supports this feature.

Describe the solution you'd like
An update for TranslateTestingModule that allows passing custom parsers to TranslateService.
Suggested Name: withParser().

Add Angular 12 support

Describe the bug
Getting the following warnings while migrating from Angular v11 => v12.

Package "ngx-translate-testing" has an incompatible peer dependency to "@angular/common" (requires "^10.0.0-rc.0 || >=10.0.0 <11.0.0" (extended), would install "12.0.1").
Package "ngx-translate-testing" has an incompatible peer dependency to "@angular/core" (requires "^10.0.0-rc.0 || >=10.0.0 <11.0.0" (extended), would install "12.0.1").

Tests break when there's a component inside another component

Describe the bug
Tests break when there's a component inside another component

To Reproduce
Steps to reproduce the behavior:

  1. Generate a new component using ng generate component
  2. Take part of the app.component.html and put it in the .html of the new component (I've taken the list element that uses the translate pipe)
  3. If you run the demo app, you can check that everything is still working
  4. But, when you run yarn run test:app you can see that there are several errors saying that some component can't find the translate pipe

Expected behavior
Everything working, both the demo app and the tests

Screenshots
I've recorded a screen cast taking the steps to reproduce the error.

Desktop (please complete the following information):

  • OS: Ubuntu 20.04
  • Browser N/A
  • Version N/A

Using require() instead of import

Is there a specific reason why you are using require() and not import?
E.g. import * as translation from '../../i18n/hu.json';

TranslateTestingModule.withTranslations(ENGLISH_LANGUAGE, ENGLISH_TRANSLATIONS)
  .withTranslations(SPANISH_LANGUAGE, SPANISH_TRANSLATIONS)
  .withTranslations(ENGLISH_LANGUAGE, require('../../assets/i18n/en.json'))

6.0.0 : Class constructor TranslateLoader cannot be invoked without 'new'

Describe the bug
After upgrading to 6.0.0 and Angular 13 I'm having this error when running my test.

To Reproduce
Setup a project with latest version of Angular, NGX Translate and ngx-tranlate-testing

Expected behavior
It shouldn't output error

Screenshots
N/A

Desktop (please complete the following information):

  • OS: Mac
  • Node 14

Thanks ! Tell me if I can help on resolving this bug

Support arrays in ngx-translate-testing

Is your feature request related to a problem? Please describe.
We use your ngx-translate-testing package for Storybook and unit-tests to mock our translations.
The TranslateTestingModule does not support arrays for translations. The following error is given during build:

    Type 'string[]' is not assignable to type 'LanguageTranslation'.
    Type 'string[]' is not assignable to type '{ [translationKey: string]: LanguageTranslation; }'.
    Index signature for type 'string' is missing in type 'string[]'.

This error is given when we try:

TranslateTestingModule.withTranslations({
          'lifecycle': {
            'customer-profile': {
              'profiles': ["profile1","profile2"]      
            },
          },
        })

Arrays are supported by the TranslateModule.

In our template we do this:

<button
      *ngFor="let profile of 'lifecycle.customer-profile.profiles' | translate; let i = index" >
      {{ profile | translate }}
    </button>
"profiles": ["profile1", "profile2", "profile3"],

Describe the solution you'd like
Allow to specify arrays just like our translation which comes from a json file.

export declare type LanguageTranslation = string | string[] | {
    [translationKey: string]: LanguageTranslation;
};

6.0.0: Unexpected value 'TranslateTestingModule' imported by the module 'DynamicTestModule'. Please add an @NgModule annotation.

Describe the bug
After upgrading to 6.0.0 and Angular 13 I'm having this error when running my tests.

To Reproduce

  • Setup a project with angular 13, ngx-translate 14 and ngx-tranlate-testing 6.0.0
  • Create a test for a component with:
TestBed.configureTestingModule({
      providers: [MyComponent],
      imports: [
        TranslateTestingModule.withTranslations({
          en: require('src/assets/i18n/en-EN.json'),
        }),
      ],
      declarations: [MyComponent],
    }).compileComponents();

Expected behavior

  • It shouldn't output error

Screenshots

  • N/A

Desktop (please complete the following information):

  • OS: Mac
  • Node 14

Provide / generate placeholders for translation texts to ease component testing.

Is your feature request related to a problem? Please describe.
We are using a following workflow to provide translations in the app:

  1. The keys are extracted during a build using ngx-translate-extract.
  2. The extracted file is uploaded to an external tool where translators provide texts in all the required languages.
  3. A scheduled job extracts the translations from that external tool and uploads it to a storage available to the running app.

This means that the translated texts are never committed into the repository along with the code and we cannot use them in tests directly.

At the same time, we would not like to tie our component tests to a specific implementation of the translation (TranslatePipe / TranslateService). We would like to still just test that the component renders the translated text, not the key itself.

The current solution we use looks something like the following:

const TRANSLATED: Record<string, string> = {
  'My text to translate': 'Mój przetłumaczony tekst'
};

describe('MyComponent', () => {
  // ...
  beforeEach(() => {
    TestBed.configureTestingModule({
      // ...
      imports: [TranslateTestingModule.withTranslations({ pl: TRANSLATED }).withDefaultLanguage('pl')]
    });
  });
  
  // ...

  it("should show translated text", () => {
    expect(allText()).toContain(TRANSLATED['My text to translate'])
  });
  
  // ...
});

While overall this works, there are at least a couple of serious pain points:

  • We need to repeat the keys in the test file and come up with some sort of translation for them. This is tedious and hurts when the texts need to change over time.
  • When the component for some reason does not translate the text we can get an unhelpful error message like Expected "A lot of text rendered by component along with My text to translate and other text" to contain "Mój przetłumaczony tekst". This does not quickly point to what exactly is wrong.
  • If the test itself has issues and the TRANSLATED object has missing / misaligned keys we get an ever worse error message like Expected "..." to contain undefined.

Describe the solution you'd like
I would like the testing tools to return a clearly identifiable text for whatever translation key it is asked for.
For example, for a key like "My translation key" it could return text like "Translation for 'My translation key'".

Ideally, when the key contains params, the values of those params would be included in the translation.
For example, if the component template contains 'My key with {{param1}} and {{param2}}' | translate: {param1: "foo", param2: "bar"}, the rendered text could be "Translation for 'My key with {{param1}} and {{param2}}' with parameters: {param1: "foo", param2: "bar"}".

If this is done, the test stub I included above could be simplified to:

describe('MyComponent', () => {
  let translateService: TranslateService;
  // ...
  beforeEach(() => {
    TestBed.configureTestingModule({
      // ...
      imports: [TranslateTestingModule]
    });
    
    translateService = TestBed.inject(TranslateService)
  });

  // ...

  it('should show translated text', () => {
    expect(allText()).toContain(translateService.instant("My text to translate"));
  });

  // ...
});

Or even:

import { translationPlaceholderFor, TranslateTestingModule } from "ngx-translate-testing";

describe('MyComponent', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      // ...
      imports: [TranslateTestingModule]
    });
  });

  // ...

  it('should show translated text', () => {
    expect(allText()).toContain(translationPlaceholderFor('My text to translate'));
  });

  // ...
});

Describe alternatives you've considered
I have considered writing a function that accepts translation keys as an array of strings and returns a TRANSLATED object as in the first example. This would still require us to repeat each translation key in the test file at least twice and would not play nicely with keys that contain parameters.

Additional context
I think this could be introduced in a backwards compatible way. If somebody already imports TranslateTestingModule.withTranslations(...)... in their testing module, those translation could still be used instead of the new, placeholder ones. Alternatively, we could provide a separate method like TranslateTestingModule.withPlaceholderTranslations() to make the feature even more explicit and opt-in.

I am happy to provide a PR that would introduce this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.