从未调用过的SpyOn订阅方法

时间:2018-08-10 12:28:37

标签: angular typescript unit-testing observable karma-jasmine

在Angular业力茉莉花中遇到单元测试问题。 我想测试构造onCreate()的{​​{1}}方法,并在提交时应调用NgbModal。问题在于,即使您将restApiServiceSpyOn一起使用,在单元测试中也不会提交。

这是我的Observable

OnCreate()

这是我的单元测试:

public onCreate() {
this.modalRef = this.modalService.open(CreateEntityFormComponent);
// input necessary settings
this.modalRef.componentInstance.tableSettings = this.parentTableSettings;
this.modalRef.componentInstance.tableColumns = modalColumns;
// subscribe for form submission
this.modalRef.componentInstance.submit.subscribe((formValue) => {
    // fire a create method
    this.restApiHelper.create(this.parentTableSettings.entityName, formValue).subscribe(
        (resp: any) => {
            const newEntityId = resp;
            // show success notification
            this.notifications.success(this.__('Entry added successfuly.'));
                }
        (err: any) => {
            // upon failure dont close the modal, just reanable form submission and show error notification
            this.modalRef.componentInstance.savingIndicator = false;
            this.errorHandler.error(err);
                }); 
    });
}

我总是得到describe(`SignallingLinkSet Component`, () => { let injector: TestBed; let comp: SignallingLinkSetComponent; let fixture: ComponentFixture<SignallingLinkSetComponent>; let restApiHelperService: RestApiHelper; beforeEach(() => { TestBed.configureTestingModule({ imports: [ CommonModule, ReactiveFormsModule, NgbModule.forRoot(), HttpClientModule, ], declarations: [ SignallingLinkSetComponent ], providers: [ RestApiHelper, HttpTestingController, NgbModal, ] }); injector = getTestBed(); fixture = TestBed.createComponent(SignallingLinkSetComponent); comp = fixture.componentInstance; restApiHelperService = fixture.debugElement.injector.get(RestApiHelper); spyOn(comp.modalService, 'open').and.callThrough(); fixture.detectChanges(); }); it('onCreate()', () => { // mock data const formData = { linksNumber: '1', name: 'test' }; const response = {SignallingLinkSet: 10846692}; const submitSpy = spyOn(comp.modalRef.componentInstance, 'submit').and.returnValue(Observable.of(formData)); spyOn(comp.restApiHelper, 'create').and.returnValue(Observable.of(response)); comp.onCreate(); // assert expect(comp.modalRef.componentInstance).not.toBeUndefined(); expect(submitSpy).toHaveBeenCalled(); expect(restApiHelperService.create).toHaveBeenCalledTimes(2); }); }); ,所以从未调用过提交模拟。 感谢您的帮助

更新:我将Expected spy submit to have been called.更改为comp.modalRef = modalService.open(CreateEntityFormComponent);,但是现在我得到spyOn(comp.modalService, 'open').and.callThrough();不确定

0 个答案:

没有答案
相关问题