Testing - Stubbing service method is undefined

有些话、适合烂在心里 提交于 2019-12-24 09:27:53

问题


I have written a very simple test on a very simple code but for some reason stub service method is undefined. When I use Jasmine Spy it works but for such a simple task. could someone please explain why is this happening (i have removed import statements just to reduce code):

businessarea-overview.component

@Component({
  templateUrl: './businessarea-overview.component.html',
  styleUrls: ['./businessarea-overview.component.css']
})
export class BusinessAreaOverviewComponent implements OnInit {
  businessArea: BusinessArea;
  businessAreaId: number;
  errorMessage: string;

  constructor(private businessAreaService: BusinessAreaService, private utilityService: UtilityService,  private route: ActivatedRoute) {
    this.businessArea = new BusinessArea();
    this.route.params.subscribe(params => {
      this.businessAreaId = +params['id'];
    });
   }

  ngOnInit() {
    if (!isNaN(this.businessAreaId)) {
      this.businessAreaService.getBusinessAreaById(this.businessAreaId)
        .subscribe(data => {
          this.businessArea = data;
        },
        error => this.errorMessage = error);
    }
  }
}

businessarea-overview.spec.ts

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

  beforeEach(async(() => {
    const authServiceSpy = jasmine.createSpyObj("AuthService", ["authenticateUser"]);
    authServiceSpy.authenticateUser.and.callFake(() => { return Observable.from([true]); });

    //const businessAreaServiceSpy = jasmine.createSpyObj("BusinessAreaService", ["getBusinessAreaById"]);
    //businessAreaServiceSpy.getBusinessAreaById.and.callFake(() => { return Observable.of(new BusinessArea()); });

        TestBed.configureTestingModule({
            declarations: [
                BusinessAreaOverviewComponent
            ],
            imports: [
                GrowlModule,
                FormsModule,
                RadioButtonModule,
                AutoCompleteModule,
                DataTableModule,
                MessagesModule
            ],
            providers: [
                { provide: Http, useValue: httpServiceStub },
                { provide: AuthService, useValue: authServiceSpy },
                { provide: UtilityService, useValue: utilityServiceStub },
                { provide: ActivatedRoute, useValue: { params: Observable.of({id: 123})} },
                { provide: BusinessAreaService, useValue: businessAreaServiceStub }
            ]
        }).compileComponents();

        fixture = TestBed.createComponent(BusinessAreaOverviewComponent);
        component = fixture.debugElement.componentInstance;
    }));

   it('should create the component', () => {
       var businessAreaService = fixture.debugElement.injector.get(BusinessAreaService);
       console.log(businessAreaService);
       fixture.detectChanges();
        expect(component).toBeTruthy();
   });
});

export class httpServiceStub {
}

export class utilityServiceStub {
   navigateTo(path: string, id: number, urlSegment){ }
}

export class businessAreaServiceStub{
     getBusinessAreaById(id: number): Observable<BusinessArea> {
        return Observable.of(new BusinessArea());
    }
}

export class routerServiceStub {
}

the commented lines in test class is the fix. when i do console.log I can clearly see the Stubbed service is injected when calling

this.businessAreaService.getBusinessAreaById

in OnInit method but getBusinessAreaById is undefined and not there.

I get below error

TypeError: this.businessAreaService.getBusinessAreaById is not a function

I know it has to do with this but cant get my head around as to why this is happening.

business-area.service.ts

@Injectable()
export class BusinessAreaService {

    constructor(private http: Http) {

    }

    saveBusinessArea(businessArea: BusinessArea): Observable<any> {
        let body = JSON.stringify(businessArea);
        let headers = new Headers(AppSettings.jsonContentTypeObject);
        let options = new RequestOptions({ headers: headers });

        if (businessArea && businessArea.id > 0)
            return this.updateBusinessArea(businessArea.id, body, options);

        return this.addBusinessArea(body, options);
    }

    private addBusinessArea(body: Object, options: Object): Observable<BusinessArea> {
        return this.http.post(AppSettings.businessAreaEndPoint, body, options)
            .map(this.extractData)
            .catch(this.handleError);
    }

    private updateBusinessArea(id: number, body: Object, options: Object): Observable<BusinessArea> {
        return this.http.put(AppSettings.businessAreaEndPoint + id, body, options)
            .map(this.extractData)
            .catch(this.handleError);
    }

    getBusinessAreaById(id: number): Observable<BusinessArea> {
        return this.http.get(AppSettings.businessAreaEndPoint + id)
            .map(this.extractData)
            .catch(this.handleError);
    }

    getAllBusinessAreas(): Observable<BusinessArea[]> {
        return this.http.get(AppSettings.businessAreaEndPoint)
            .map(this.extractData)
            .catch(this.handleError);
    }

    private extractData(response: Response) {
        let body = response.json().items || response.json();
        return body || {};
    }

    private handleError(error: Response) {
        console.log(error);
        return Observable.throw(error || "500 internal server error");
    }
}

回答1:


change { provide: BusinessAreaService, useValue: businessAreaServiceStub } to { provide: BusinessAreaService, useClass: businessAreaServiceStub }



来源:https://stackoverflow.com/questions/44433779/testing-stubbing-service-method-is-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!