0

I have a NativeScript Code-Sharing project. I wish to use Karma unit testing against the web version using ng test. This fails due to a .tns version of a service being wrongly imported when building the tests.

Following are steps to recreate the problem in a minimal NativeScript Code-Sharing project.

  • Create a new NativeScript Code-Sharing project

    $ ng new -c=@nativescript/schematics ns-shared-test --shared
    
  • Enter the project folder

    $ cd ns-shared-test
    
  • Generate a new service

    $ ng generate service services/my-service
    
  • Generate a new component

    $ ng generate component my-component
    
  • Modify my-component.component.ts to use my-service

    • Add at top of file:

      import { MyServiceService } from '@src/app/services/my-service.service';
      
    • And replace the constructor:

      constructor( private myService:MyServiceService ) { }
      
  • Run unit tests

    $ ng test
    
    • Observe that the test passes
  • Split my-service

    $ cp src/app/services/my-service.service.ts src/app/services/my-service.service.tns.ts
    
  • Modify my-service.service.tns.ts to use something NativeScript specific

    • Add at the top of file:

      import { Color } from 'tns-core-modules/color/color';
      
    • And replace the constructor:

      constructor() { new Color('white'); }
      
  • Run unit tests

    $ ng test
    
    • Observe that the test fails while loading NativeScript modules
don
  • 1,497
  • 1
  • 13
  • 27

1 Answers1

1

A solution which worked for me was:

  • rename 'my-service.service.ts', to my-service.service.web.ts
  • in my web component import { MyServiceService } from '@src/app/services/my-service.service.web';
  • in the spec file import { MyServiceService } from '@src/app/services/my-service.service.web'

The ng test command should now work

  • This does seem to work as you suggested. Are there any drawbacks of taking this approach? Does this affect the Code-Sharing strategy in any way? Will the unit tests still work on mobile? – don Jan 13 '20 at 13:18
  • Sorry for this late response. The drawback will probably be, that in every service or component you create you must explicitly say it is for web or mobile. If you have a component and you have a service injected via the constructor. In that service you have some mobile library, you have to create another service for the mobile part. – David Kroese Mar 02 '20 at 09:09