1

I want to test my provider class, so I am unable to write spec for providers.

My provider is as follows:

service.ts

//imports are done correctly.

@Injectable()
export class Service {

   constructor(private http: Http) { }

    getGoogle():Observable<any> {
        console.log("Inside service");
        return this.http.get('https://jsonplaceholder.typicode.com/posts/1');
    }
}

My page.ts is as follows:

page.ts

//imports are done correctly.

export class Page1 {

  constructor(private service: Service, private navCtrl: NavController) { }
  async get() {
    console.log("inside get method");
    const data =  await this.service.getGoogle().toPromise();
      console.log('The response is' , data);
       }
}

service.spec.ts

//imports are done correctly

describe('Service', () => {
    let comp: Service;
    let fixture: ComponentFixture<Service>;
    let de: DebugElement;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [],
            imports: [
                IonicModule.forRoot(Service)

            ],
            providers: [Http]
        }).compileComponents();

    }));
    beforeEach(() => {
        fixture = TestBed.createComponent(Service);
        comp = fixture.componentInstance;
        de = fixture.debugElement;
    });
    afterEach(() => {
        fixture.destroy();
    });
it('test the http request to te server', ()=>{
             //code to test http request of the Service class

});

});

All the imports are done correctly, only the logic to test the getGoogle() with http.get() needs to be tested.

Please help or share some links or tell me some steps in order to do testing of this ionic2 content.

Thank you

user8348978
  • 81
  • 1
  • 1
  • 7

1 Answers1

0

This Rangle tutorial is a great place to start.

You can mock your providers like this

class MockService {
  public data = 'Test data';

  getGoogle() {
    return Observable.of(this.data);
  }
}

Provide it to TestBed

TestBed.configureTestingModule({
  declarations: [
    Page1
  ],
  providers: [
    { provide: Service, useClass: MockService }
  ]
});

And use tick and fakeAsync to simulate the async operation

it('should get', fakeAsync(() => {
  comp.get();
  tick();
  // If you want to assign the data to a class variable. If not, change the
  // condition for whatever you want to test the method to do.
  expect(comp.data).toEqual('Test data');
}));
emroussel
  • 1,077
  • 11
  • 19