mercredi 31 août 2016

Testing a service in angular2

My app appModule has

@NgModule({
    imports: [
       ...
  ],
  providers: [
    SdkService,
    MyOtherService
  ],
  bootstrap: [
     ...
  ]
})

MyOtherService which used the SdkService looks look this

import {SdkService} from '../sdkService';
@Injectable()
export class MyOtherService {
 constructor(
    private _sdk: SdkService
    ) {}

 public myMethod(): Observable<any[]> {
    ....}
}

Now I'm trying to test MyOtherService.MyMethod and cannot figure it out. I need that sdk to be a Mock service.

import { SdkService } from '../sdkService';
import { MyOtherService } from './MyOtherService'; 

describe('Testing Service', () => {
    beforeEach(async((MyOtherService: MyOtherService) => {
        TestBed.configureTestingModule({
            providers: [{
                provide: SdkService,
                useClass: MockSdkService
            }, MockSdkService],
            imports: [
                MyOtherService
            ]
        });
    }));

    it('should work', () => {
        let fixture: ComponentFixture<MyOtherService> = TestBed.createComponent(MyOtherService);
        fixture.detectChanges();

        fixture.componentInstance.myMethod().toPromise().then( (result) => {
            expect(result.prop.length).toBe(1);
        });
    });

});

Should I even be using createcomponent to test a service?

Aucun commentaire:

Enregistrer un commentaire