menu

Questions & Answers

Setup service provider on unit testing

I have a component the following:

TS

export class CashFlowSalariesComponent implements OnInit, OnChanges {

...

constructor(
    public apiService: ApiService,
    private modalService: NgbModal,
    private toastr: ToastrService
  ) {}

  ngOnInit() {

  }
}

Now I want to create a unit testing for it so I try

.spec.ts

describe('CashFlowSalariesComponent', () => {
    let component: CashFlowSalariesComponent;
    let fixture: ComponentFixture<CashFlowSalariesComponent>;
    let apiService: ApiService;


  
    beforeEach(async(() => {
      TestBed.configureTestingModule({
        schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
        imports: [
                            [RouterModule.forRoot([])],
                            RouterTestingModule,
                            FormsModule,
                            ReactiveFormsModule,
                            BrowserModule,
                            HttpClientTestingModule,
                        ],
        declarations: [ 
            CashFlowSalariesComponent,
        ],
        providers: [{provide: apiService}]

      })
      .compileComponents();
    }));
  
    beforeEach(() => {
      fixture = TestBed.createComponent(CashFlowSalariesComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
    });
  
    it('should create', () => {
      expect(component).toBeTruthy();
    });

But this is throwing an error message:

NullInjectorError: StaticInjectorError(DynamicTestModule)[CashFlowSalariesComponent -> ApiService]: StaticInjectorError(Platform: core)[CashFlowSalariesComponent -> ApiService]: NullInjectorError: No provider for ApiService!

As you can see, I tried to set the ApiService as a provider, but it did not work; what am I doing wrong?

Answers(2) :

provide should receive a class, then you can either also declare the useClass or the useValue if you want to stub it.

providers: [{provide: ApiService, useValue: {methodExample: ()=>null}}]

If you don't want to mock the service, you could just add the class directly to the providers:

 providers: [ApiService]

Correct syntax to define dependency provider is:- [{ provide: apiService, useClass: ApiService }] And yes instead of useClass you can use - useExisting , useFactory, useValue properties. Please check on this page:- https://angular.io/guide/dependency-injection-providers