单元测试:Angular4:Jasmine:当控件从假服务方法返回时,订阅中未定义响应

单元测试:Angular4:Jasmine:当控件从假服务方法返回时,订阅中未定义响应,angular,unit-testing,karma-jasmine,Angular,Unit Testing,Karma Jasmine,我通过在spec文件中创建服务的mock类来模拟服务。在我的组件中,有一个调用数据服务的函数。当spec运行时,它成功地转到mock方法,但不返回数据,即,可观察的内部内容。 对于我的it案例,我得到的错误是“预期未定义为真实” 规格文件 从'@angular/Http'导入{BaseRequestOptions,Http,HttpModule,Response,ResponseOptions}; 从'@angular/http/testing'导入{MockBackend}; 从“./add

我通过在spec文件中创建服务的mock类来模拟服务。在我的组件中,有一个调用数据服务的函数。当spec运行时,它成功地转到mock方法,但不返回数据,即,可观察的内部内容。 对于我的it案例,我得到的错误是“预期未定义为真实”

规格文件


从'@angular/Http'导入{BaseRequestOptions,Http,HttpModule,Response,ResponseOptions};
从'@angular/http/testing'导入{MockBackend};
从“./add serviceCenter repair authority.component”导入{AddServiceCenter repair authority component};
从'@angular/core/testing'导入{TestBed,ComponentFixture,async,inject};
从“@angular/platform browser”导入{By}”;
从“@angular/core”导入{DebugElement,无_错误_模式};
从'@angular/forms'导入{FormsModule};
从'priming/priming'导入{SelectItem,MultiSelectModule,CalendarModule};
从“核心用户界面”导入{coreimodule};
从“@angular/router/testing”导入{RouterTestingModule};
从'@angular/Router'导入{Router};
从“../services/scooterRepair.service”导入{scooterRepairService};
从'core shared/core.service'导入{StorageService};
从“../models/serviceCenter repair add.model”导入{serviceCenter repair add};
从“@angular/platform browser/animations”导入{BrowserAnimationsModule};
从“rxjs/Observable”导入{Observable};
从“../models/missingScooterRepair”导入{IMissingscooterRepair};
从“../models/serviceCenter repair record.model”导入{serviceCenter repair record};
从“../models/RepairClass.model”导入{RepairClass};
从“../models/RepairCode.model”导入{RepairCode};
从“../models/serviceCenter repair search.model”导入{serviceCenter repair search};
从“../models/scooter repair search.model”导入{scooterRepairSearch};
从“../models/scooter repair record.model”导入{scooterRepairRecord};
fdescribe('AddserviceCenterRepairAuthorityComponent',()=>{
let夹具:组件夹具;
设de:DebugElement;
让el:HTMLElement;
让路由器:路由器;
let comp:AddserviceCenterRepairAuthorityComponent;
类MockscooterRepairService{
标题:标题=新标题();
私人帮助='';
专用scooterRepairAuthorityApiurl=http://localhost:3000/scooterRepairAuthority';
构造函数(){
append('appuser','devnxd');
}
公共提交服务中心修复(服务中心修复添加记录):可观察{
if(serviceCenterRepairAddRecord.hasOwnProperty()){
return Observable.throw('发生错误,请重试');
}否则{
可观测收益(
{
'isSuccess':true,'results':[{'recordId':1}],'recordId':1
});
}
}
克隆(对象:任意){
返回JSON.parse(JSON.stringify(object));
}
public getscooterInitials():可观察{
可观测收益(
{
});
}
public getThresholdValues(isAmountOnly:boolean):可观察{
可观测收益(
{
});
}
public getRepairClassItems():可观察{
可观测收益(
{
});
}
public getRepairCodeItems():可观察{
可观测收益(
{
});
}
public getPercentageApprovalItems():可观察{
可观测收益(
{
});
}
公共getUnitCountItems(scooterInitials:string[]):可观察{
可观测收益(
{
});
}
公共getscooterClassItems(scooterInitials:string[]):可观察{
可观测收益(
{
});
}
public getFacilityItems():可观察{
可观测收益(
{
});
}
公共搜索ScooterPairs(ScooterPairSearch:ScooterPairSearch):可观察{
可观测收益(
{
});
}
public SearchServiceCenter修复(strFacility:string[],strStatusCode:string[],strthreshold:string[],LastUpdateDate:Date,
插入日期:日期,生效开始日期:日期,生效结束日期:日期){
可观测收益(
{
});
}
公共submitscooterRepair(scooterRepairRecord:scooterRepairRecord,isValidated:boolean=true):可观察{
可观测收益(
{
});
}
公共搜索丢失ScooterRepairs():可见{
可观测收益(
{
});
}
私有getDefaultHeaders():标题{
常量头:头=新头();
//headers.append('appuser',this.auth.user.userName);
append('appuser','devws');
headers.append('Content-Type','application/json');
//append('Cache-Control','no-Cache');
//append('Pragma','no cache');
返回标题;
}
私有句柄错误(错误:响应){
返回Observable.throw(error.statusText | | |“服务器错误”);
}
私有提取数据(res:Response,isResultOnly:boolean=true){
const data=res.json();
控制台日志(数据);
//const data=res.json();//这将在实际调用服务时使用
if(数据发布成功){
返回isResultOnly?数据。结果:数据;
}else if(data.isException&&data)
import { BaseRequestOptions, Http, HttpModule, Response, ResponseOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { AddserviceCenterRepairAuthorityComponent } from './add-serviceCenter-repair-authority.component';
import { TestBed, ComponentFixture, async, inject } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { SelectItem, MultiSelectModule, CalendarModule } from 'primeng/primeng';
import { CoreUIModule } from 'core-ui';
import { RouterTestingModule } from '@angular/router/testing';
import { Router } from '@angular/router';
import { scooterRepairService } from '../services/scooterRepair.service';
import { StorageService } from 'core-shared/core.service';
import { serviceCenterRepairAdd } from '../models/serviceCenter-repair-add.model';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { Observable } from 'rxjs/Observable';

import { IMissingscooterRepair } from '../models/missing-scooter-repair';
import { serviceCenterRepairRecord } from '../models/serviceCenter-repair-record.model';
import { RepairClass } from '../models/repairClass.model';
import { RepairCode } from '../models/repairCode.model';
import { serviceCenterRepairSearch } from '../models/serviceCenter-repair-search.model';
import { scooterRepairSearch } from '../models/scooter-repair-search.model';
import { scooterRepairRecord } from '../models/scooter-repair-record.model';



fdescribe('AddserviceCenterRepairAuthorityComponent', () => {
    let fixture: ComponentFixture<AddserviceCenterRepairAuthorityComponent>;
    let de: DebugElement;
    let el: HTMLElement;
    let router: Router;
    let comp: AddserviceCenterRepairAuthorityComponent;

    class MockscooterRepairService {
        headers: Headers = new Headers();
        private help = '';
        private scooterRepairAuthorityApiurl = 'http://localhost:3000/scooterRepairAuthority';

        constructor() {
            this.headers.append('appuser', 'devnxd');
        }

        public submitserviceCenterRepair(serviceCenterRepairAddRecord): Observable<any> {
            if (serviceCenterRepairAddRecord.hasOwnProperty()) {
                return Observable.throw('Error occurred, please try again');
            } else {
                return Observable.of(
                    {
                        'isSuccess': true, 'results': [{ 'recordId': 1 }], 'recordId': 1
                    });


            }
        }


        clone(object: any) {
            return JSON.parse(JSON.stringify(object));
        }

        public getscooterInitials(): Observable<SelectItem[]> {

            return Observable.of(
                {

                });
        }

        public getThresholdValues(isAmountOnly: boolean): Observable<SelectItem[]> {
            return Observable.of(
                {

                });
        }
        public getRepairClassItems(): Observable<SelectItem[]> {
            return Observable.of(
                {

                });
        }
        public getRepairCodeItems(): Observable<SelectItem[]> {
            return Observable.of(
                {

                });
        }
        public getPercentageApprovalItems(): Observable<SelectItem[]> {
            return Observable.of(
                {

                });
        }


        public getUnitCountItems(scooterInitials: string[]): Observable<SelectItem[]> {
            return Observable.of(
                {

                });
        }

        public getscooterClassItems(scooterInitials: string[]): Observable<SelectItem[]> {
            return Observable.of(
                {

                });
        }

        public getFacilityItems(): Observable<SelectItem[]> {
            return Observable.of(
                {

                });
        }


        public searchscooterRepairs(scooterRepairSearch: scooterRepairSearch): Observable<scooterRepairRecord[]> {
            return Observable.of(
                {

                });
        }


        public searchserviceCenterRepairs(strFacility: string[], strStatusCode: string[], strthreshold: string[], lastUpdatedDate: Date,
            insertDate: Date, effectiveStartDate: Date, effectiveEndDate: Date) {
            return Observable.of(
                {

                });
        }



        public submitscooterRepair(scooterRepairRecord: scooterRepairRecord, isValidated: boolean = true): Observable<any> {
            return Observable.of(
                {

                });
        }
        public searchMissingscooterRepairs(): Observable<IMissingscooterRepair> {
            return Observable.of(
                {

                });
        }

        private getDefaultHeaders(): Headers {
            const headers: Headers = new Headers();
            // headers.append('appuser', this.auth.user.userName);
            headers.append('appuser', 'devvws');
            headers.append('Content-Type', 'application/json');
            //   headers.append('Cache-Control', 'no-cache');
            // headers.append('Pragma', 'no-cache');
            return headers;
        }



        private handleError(error: Response) {
            return Observable.throw(error.statusText || 'Server error');
        }

        private extractData(res: Response, isResultOnly: boolean = true) {
            const data = res.json();
            console.log(data);
            // const data = res.json(); // This will be used when actual service calling
            if (data.isSuccess) {
                return isResultOnly ? data.results : data;
            } else if (data.isException && data.errors.length > 0) {
                this.handleError(data.errors[0]);
            }
            return {};
        }
        convertFeatureListToNGPrimeDropdownOptions(list: any, labelKey, valueKey): SelectItem[] {
            const data = this.clone(list);
            const options: SelectItem[] = [];
            for (let i = 0; i < data.length; i++) {
                this.changeKeyName(data[i], labelKey, 'label');
                this.changeKeyName(data[i], valueKey, 'value');
                options.push(data[i]);
            }
            return options;
        }

        private changeKeyName(obj: any, oldKey: string, newKey: string): any {
            if (obj.hasOwnProperty(oldKey)) {
                obj[newKey] = obj[oldKey];
                delete obj[oldKey];
            }
            return obj;
        }

    }

    // async beforeEach
    beforeEach(async(() => {
        class RouterStub {
            navigateByUrl(url: string) { return url; }
        }




        TestBed.configureTestingModule({
            declarations: [AddserviceCenterRepairAuthorityComponent], // declare the test component
            schemas: [NO_ERRORS_SCHEMA],
            providers: [scooterRepairService, MockBackend, StorageService,
                BaseRequestOptions,
                {
                    provide: Http,
                    useFactory: (backend, options) => new Http(backend, options),
                    deps: [MockBackend, BaseRequestOptions]
                },
                { provide: scooterRepairService, useClass: MockscooterRepairService },
            ],
            imports: [BrowserAnimationsModule, FormsModule, MultiSelectModule, CalendarModule, CoreUIModule, RouterTestingModule]

        })
            .compileComponents();  // compile template and css
    }));

    // synchronous beforeEach -- used if component is having external templates
    beforeEach(() => {
        fixture = TestBed.createComponent(AddserviceCenterRepairAuthorityComponent);
        comp = fixture.componentInstance;
    });

    it('component is created', () => {
        expect(comp).toBeTruthy();
    });

    xit('unsuccessful should be true when serviceCenterRepairAddRecord is empty object', () => {

        comp.serviceCenterRepairAddRecord = <serviceCenterRepairAdd>{};
        const recordAddedSuccessfully = comp.onAddserviceCenterRepairClick();
        fixture.detectChanges();
        expect(recordAddedSuccessfully).toBe(2);
    });


    it('unsuccessful should be true when serviceCenterRepairAddRecord is not empty object', () => {

        comp.serviceCenterRepairAddRecord = <serviceCenterRepairAdd>{
            'facilityId': 1, 'statusCode': '200', 'thresholdAmount': 432,
            'effectiveStartDate': new Date(), 'effectiveEndDate': new Date(), 'builtEndDate': new Date()
        };
        comp.unsuccessful = 0;
        const recordAddedSuccessfully = comp.onAddserviceCenterRepairClick();
        fixture.detectChanges();
        expect(recordAddedSuccessfully).toBeTruthy();
    });


    xit('on cancel scooter repair click', () => {
        const spy = spyOn((<any>comp).router, 'navigateByUrl');
        comp.onCancelserviceCenterRepairClick();

        fixture.detectChanges();
        expect(spy).toHaveBeenCalledWith('cra');

    });
});
onAddserviceCenterRepairClick() {
        this.scooterRepairService.submitserviceCenterRepair(this.serviceCenterRepairAddRecord).subscribe(
            response => this.submitedSuccess = response.recordId
            ,
            error => this.errorMessage = <any>error,
            () => {
                if (this.submitedSuccess === -1) {
                    alert('Record cannot be added');
                    this.unsuccessful = 2;
                } else {
                    this.unsuccessful = 1;
                    this.router.navigate(['cra'], { queryParams: { from: 'serviceCenterRepairSubmit' } });
                }
            }

        );

    }
return Observable.of([{

                   }]);