angularunit-testingkarma-jasmineangular-unit-testtestbed

How to reuse Mock dependencies in Angular Unit Test?


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 
    },
  ],
  }),
}
}

Solution

  • 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.