简体   繁体   中英

Angular 4, unit testing

I have one component which consists of one method which internally calls service and I need to do unit testing for the same.

Component.ts:

constructor(
    private formUtils: MeasureFormService,
}

getList() {
    this.formUtils.getList()
        .subscribe((data) => {
            this.memberDetails = data.MemberDetails;
            this.chaserDetails = data.RelatedChaserDetails;
        }, error => {
        });
}

MeasureFormService.ts:

getList() {
    return this._httpWrapperService.Get('../../../../../assets/json/overread-accept.json')
    .map((data: any) => {
        return data;
    });
}

I need to unit test the component method which calls service.

Try this.

describe('Test', () => {

  let component: NotificationComponent;
  let fixture: ComponentFixture<YourComponent>;
  let measureFormService: MeasureFormService;
  let mockMeasureFormService;
  let listSubject;

  beforeEach(async(() => {

    listSubject = new Subject < any > ();
    mockMeasureFormService = {
      getList: () => {
        return listSubject;
      }
    };

    TestBed.configureTestingModule({
      declarations: [YourComponent],
      providers: [{provide: MeasureFormService, useValue: mockMeasureFormService}]
    }).compileComponents();

    fixture = TestBed.createComponent(YourComponent);
    component = fixture.componentInstance;
    notificationService = TestBed.get(NotificationService);
  }));

  it('should have a list of objects you need', () => {
    component.getList();
    listSubject.next(//just put a test object you are getting from the service);
    fixture.detectChanges();
    expect(component.memberDetails).toEqual(//service response);
  });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM