1

I'm writing unit test in Angular, I am mocking all our services in all the specs repeatly, the TestBed.configureTestingModule is having same code in all the spec files. is it possible to move this TestBed.configureTestingModule and Mock dependencies to some common file and can be inject/use anywhere we want?

describe(()=>{
 @Injectable({ providedIn: 'root' })
 class MockFirstService {
 constructor() { };
 show() { };
 hide() { }; 
 }
@Injectable({ providedIn: 'root' })
class MockSecondWebApiService extends ApiBaseService {
constructor(http: HttpClient
  , blockUI: BlockUIService
) {
  super(http, blockUI, cache, { baseUrl: baseUrl });
}
}
  beforeEach(()=>{
 TestBed.configureTestingModule({
  imports: [RouterTestingModule, HttpClientTestingModule],
  providers: [
    Injector,
    ApplicationRef,
    CacheService,
    LocalStorageProvider,
    {
      provide: FirstService ,
      useClass: MockFirstService 
    },
    
    {
      provide: SecondWebApiService ,
      useClass: MockSecondWebApiService 
    },
  ],
  }),
}
}
Cegone
  • 489
  • 1
  • 9
  • 23

1 Answers1

3

Yes, you can. Don't use @Injectable for MockServices . Simply create a stub folder and create all MockServices (first.service.stub.ts) inside that folder.Make sure to export all Mock services.

export class MockFirstService {
   show() { };
   hide() { }; 
}

Just import it in component.spec files and use it with useClass.

Shashank Vivek
  • 16,888
  • 8
  • 62
  • 104
  • Yes, I have tried and it's working great. I'm able to reuse the mock dependencies in my all other spec files, I have moved those MockServices (without inject decorator) and TestBed.configureTestingModule to a separate file, and I'm able to use/import in all my spec files. Thanks you so much. Sorry I forgot to mark this as accepted answer. – Cegone Aug 16 '20 at 04:42