Ankit Garg
Ankit Garg

Reputation: 149

How to import or inject AngularJS services in Angular 2 in Unit testing

I have one service of my own in AngularJS. I have used it in one of my component in Angular 2. Now when i write unit test for the component I am not able to import or inject that service. Can anyone help me out here with this issue.

Upvotes: 0

Views: 210

Answers (1)

abdul subaan
abdul subaan

Reputation: 91

You will need to set up the test using the Angular TestBed and inject the service.

import { TestBed, async, ComponentFixture } from '@angular/core/testing';

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

  beforeEach(async(() => {

    TestBed.configureTestingModule({
       imports: [
         AppModule
       ],
       declarations: [ 
       ],
       providers: [
       ]}).compileComponents()
      .then(() => {
         fixture = TestBed.createComponent(TestComponent);
         comp = fixture.componentInstance;

         service = TestBed.get(AppService);
      });
   }));
});

Call a service and use spy,

 it('should fetch the cluster list on init', async(() => {
    expect(service.getList).toHaveBeenCalled();
});

Upvotes: 1

Related Questions