Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 testing: How to provide services without their nested dependencies?

I have a ComponentA that uses an ServiceA. I'm writing a test for ComponentA, adding ServiceA into testbed providers. I run the test and get following error:

StaticInjectorError(DynamicTestModule)[ServiceA -> ServiceB]
NullInjectorError: No provider for ServiceB!

I add ServiceB to providers. I run the test again and now I get:

StaticInjectorError(DynamicTestModule)[ServiceB -> ServiceC]
NullInjectorError: No provider for ServiceC!

My project has many nested dependencies, all services have @Injectable decorator. How can I avoid providing long list of nested services?

like image 478
Kirill Avatar asked Nov 01 '25 15:11

Kirill


1 Answers

In your .spec.ts file:

 providers: [
     {provide: YourService, useClass: YourMockService},
  ]

YourMockService will have the same methods as YourService but will just be typically empty methods. Here's a mock service:

import { Injectable } from '@angular/core'

@Injectable()
export class YourMockService {

  get user() {
    // this is mock data
    return {username: 'fred'}
  }

  public getFromLocalStorage(k: string) {
    return []
  }
}

YourService will have these same methods and getters but will, for example, perform HTTP requests, etc to get the username.

like image 122
danday74 Avatar answered Nov 04 '25 06:11

danday74



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!