0

I have written a service MyService and a mocked version of it – MyServiceMock, for unit tests providing and using the mocked service's result until my BE is ready.

I used MyService as alias of MyServiceMock, so I will not have to change my code in the future when the BE is ready:

In my services module I use:

import { MyServiceMock as MyService } from './my-service/my-service-mock.service';

const providers: Array<Provider> = [
  MyService,

...

And the same in my components:

import { MyServiceMock as MyService } from './my-service/my-service-mock.service';

...

 constructor(
   myServce: myService,

...

And it worked fine with ng serve and ng build... until I served the build. There was a runtime error in the browser MyService is undefined. But note that when served through Angular ng serve all worked fine. And there were no warnings and errors in the ng build | ng build --prod build processes.

The solution below is simple but I would appreciate any explanations of that.

Thanks!

Anton Mitsev
  • 602
  • 9
  • 15

2 Answers2

3

Instead of faking an import you can simply tell Angular to provide your fake service when the real one is requested. A StackBlitz as an example.

in app.module.ts in the providers:

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ],
  providers: [
    {
      provide: RealService,
      useClass: FakeService
    }
  ]
})
export class AppModule { }

Now every time the RealService is requested the fake service will be served instead.

Giovani Vercauteren
  • 1,898
  • 13
  • 22
0

Solution:

In the services module we provide the mocked service as-is, without alias. And we use alias only in the components:

import { MyServiceMock } from './my-service/my-service-mock.service';

const providers: Array<Provider> = [
  MyServiceMock,

...
Anton Mitsev
  • 602
  • 9
  • 15