1

what i have : Service provider depends on Http, need to be tested

MyService.ts :

@Injectable()
export class MyService {
 constructor(private http: Http) {
 }

 someFunction() {
   return this.http.get(URL)
   .map((res: Response) => {
    res.json();
   });
 }
} 

MyComponent.ts:

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})

export class MyComponent implements OnInit {
  constructor(private myService: MyService) {}
}

When i run the ng test , the error

No http provider for myComponent appears , MyService should be created

MyComponent.spec.ts :

 describe('MyComponent', () => {
   let component: MyComponent;
   let fixture: ComponentFixture<MyComponent>;

   beforeEach(async(() => {
     TestBed.configureTestingModule({
       imports: [
         HttpModule
       ],
       declarations: [ MyComponent],
       providers: [
         MockBackend,
         BaseRequestOptions,
         {
           provide: HttpClient,
           useFactory: (backendInstance: MockBackend, defaultOptions:           BaseRequestOptions) => {
             return new Http(backendInstance, defaultOptions);
           },
           deps: [MockBackend, BaseRequestOptions]
         },
         MyService
       ]
     })
     .compileComponents();

   }));

   beforeEach(() => {
     fixture = TestBed.createComponent(MyComponent);
     component = fixture.componentInstance;
     // fixture.detectChanges();
   });

   it('should be created', () => {
     expect(component).toBeTruthy();
   });
 });

what i tried All what i tried is there ! i also read about MockBackend and buid it in the service as this link shows ! but it didnt worked for me !

Any help ?

belhadj haythem
  • 622
  • 2
  • 6
  • 16

1 Answers1

1

Actually i was missing the import HTTP module , provide HTTP , ConnectionBackend in the service.spec.ts file, not only in the component.spec.ts file.

belhadj haythem
  • 622
  • 2
  • 6
  • 16
  • +1. Thanks saved me an hour . why do we need to include HTTPModule in service spec even it has mentioned in the component spec. If service of the component will be spied in component spec then why we have explicitly import in service spec ? – zulu Feb 13 '18 at 04:01