简体   繁体   English

Angular 2-如何模拟在组件中被调用的服务?

[英]Angular 2 - how do I mock a service being called in a component?

I have a component which calls a service. 我有一个调用服务的组件。 I am trying to create a test first to see if the component actually gets created. 我试图先创建一个测试,以查看该组件是否真正被创建。 I am trying to mock the service class but keep getting errors. 我正在尝试模拟服务类,但不断出错。 I keep getting: "catch is not a function". 我不断得到:“ catch不是函数”。 I have added every possible reference I can find: 我添加了所有可能找到的参考资料:

import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

Here is my code: 这是我的代码:

from my component: 从我的组件:

     ngOnInit():void{

           this.bindCustomerId();       
           this.bindEmploymentDetails();       
        }

private bindEmploymentDetails(){

        this.reviewService.getEmploymentDetails(this.reviewId)
        .catch(this.handleError)
        .subscribe(
            (employmentDetails: EmploymentInfo[]) =>
            {               

                 this.employmentDetails = employmentDetails;      
                 this.bindEmploymentDetailsVisibility(this.employmentDetails);
            }
        );        
    }   

My test: 我的测试:

describe('EmploymentDetailsComponent', () => {

  let component: EmploymentDetailsComponent;
  let fixture: ComponentFixture<EmploymentDetailsComponent>;
  let config: Route[] = [];

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
          EmploymentDetailsModule,
          RouterTestingModule.withRoutes(config),
          FormsModule,
          BrowserModule,
          HttpModule,
      ],
      declarations: [  ],
      providers:[
          {
              provide:CustomerService,
              useClass: mockCustomerService
          },
          {
              provide: ReviewService,
              useClass: ReviewServiceMock
          },
          {
              provide: LookUpService,
              useClass: mockCustomerService
          }          
      ]
    })
     .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(EmploymentDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  });

  it('should create', () => {

    expect(component).toBeTruthy();    
  });

});

I have created a mock class for ReviewServiceMock with all the same methods. 我已经使用所有相同的方法为ReviewServiceMock创建了一个模拟类。

import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class ReviewServiceMock implements IReviewService{

private apiUrl: string;            



public createNewReview(customerId: number): Observable<ReviewResponse>{

    return null;
}

public getPersonalInfo(reviewId: number): Observable<PersonalInfo[]>{

    return null;
}

public getPersonalInfoForSingleCustomer(reviewId: number, customerId: number): Observable<PersonalInfo>{

    return null;
}

public getContactInfo(reviewId: number) : Observable<ContactInformation[]>{

    return null;
}

public getContactInfoForSingleCustomer(reviewId: number, customerId : number) : Observable<ContactInformation>{

    return null;
}

public saveContactInfo(contactInfo: ContactInformation, customerId : number, reviewId: number): Observable<any>{

    return null;
}

public savePersonalInfo(personalInfo: PersonalInfo, customerId : number, reviewId: number){

    return null;
}


public getEmploymentDetails(reviewId : number):Observable<EmploymentInfo[]> {

    var mm = JSON.parse(
            `[
{
    "CustomerId": 1,
    "EmployerName": "TMG",
    "EmployerAddress": "Mosley road",
    "EmploymentStartDate": "2016-12-28T13:49:36.317Z",
    "EmploymentType": {
    "Id": 1,
    "Description": "Programmer"
    },
    "OccupationType": {
    "Id": 0,
    "Description": "string"
    },
    "JobTitle": {
    "Id": 0,
    "Description": "string"
    },
    "EstimatedMonthlyIncome": 0,
    "CustomerPayingNationalInsurance": true,
    "CustomerWorkingOver16HoursAWeek": true,
    "AffectedByInsolvency": true
}
]`        );


}

public getEmploymentDetailsForSingleCustomer(reviewId : number, customerId : number):Observable<EmploymentInfo>{

    return null;
}

public saveEmploymentDetails(employmentDetails: EmploymentInfo, reviewId: number){

    return null;
}

public confirmEmploymentDetails(reviewId: number, customerId: number){        

    return null;
}

public saveCustomerDependant(customerDependant:CustomerDependant, reviewId:number){
    return null;

}

public getCustomerDependant(reviewId: number, dependantId:number){
    return null;
}

public getAllDependants(reviewId: number){
    return null;
}

public catch()
{

}

public deleteDependant(reviewId: number, dependantId:number){
    return null;
}

public getHomeOwnerAndTenantInfoForReview(reviewId: number){
    return null;
}

public saveHousingInfoMultipleCustomer(reviewId:number,housingInfo:any){
    return null;
}

public getCurrentReview(customerId: number): Observable<ReviewResponse>{
    return null;
}

} }

You need to implement your ReviewServiceMock class. 您需要实现ReviewServiceMock类。 Let getEmploymentDetails and all other methods return an empty observerable. getEmploymentDetails和所有其他方法返回一个空的observable。 -> return Observable.of([]); -> return Observable.of([]);

The problem is that getEmploymentDetails returns null and catch is indeed not a function on null 问题是getEmploymentDetails返回null, catch实际上不是null上的函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何模拟在 Angular 中的组件声明中调用的方法? - How do I mock a method that is called in my component's declaration in Angular? 如何在正在测试的组件的OnInit中调用的测试文件中模拟服务? - How to mock a service in a test file that is being called in OnInit of the component being tested? Angular Unit test-如何在商店分派期间模拟由ngrx / effect调用的组件中的提供程序 - Angular Unit test - how to mock a provider in component which was being called by ngrx/effect during store dispatch Angular Integration测试:测试发出其他组件的事件时调用的函数,如何模拟事件数据? - Angular Integration test: testing a function that is called when event from other component is emitted, how do I mock the event data? 组件规范 (Karma) 中未调用 Angular Mock 服务 - Angular Mock Service is not getting Called in Component Spec (Karma) angular2 测试,我如何模拟子组件 - angular2 test, how do I mock sub component 如何使用 Jasmine 在 Angular 中模拟服务依赖项? - How do I mock a service dependency in Angular with Jasmine? 如何测试是否从组件角度调用了服务 - How to test if a service is called from the component in angular 测试角度2组件时如何模拟@injected服务? - How to mock an @injected service when testing an angular 2 component? 如何在 Angular 组件中模拟服务 function 以进行单元测试 - How to mock service function in Angular component for unit test
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM