简体   繁体   English

打字稿中的角度2 - 茉莉花 - 测试方法

[英]angular 2 - jasmine- test methods in typescript

i have written a simple mock services to test a method(Changed()) in typescript file (EditUser.ts) 我编写了一个简单的模拟服务来测试typescript文件中的方法(Changed())(EditUser.ts)

I am getting the following error when try to execute the edituser.spec.ts 尝试执行edituser.spec.ts时出现以下错误

TypeError: Cannot read property 'changed' of undefined
    at Object.eval (http://localhost:3000/app/Tracker/EditUserAdmin/EditUser.spec.js:94:12)
    at attemptSync (http://localhost:3000/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1886:24)
    at QueueRunner.run (http://localhost:3000/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1874:9)
    at http://localhost:3000/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1898:16
    at http://localhost:3000/node_modules/jasmine-core/lib/jasmine-core/jasmine.js:1842:9
    at http://localhost:3000/node_modules/angular2/bundles/testing.dev.js:2116:15
    at ZoneDelegate.invoke (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:390:29)
    at Zone.run (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:283:44)
    at http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:635:58
    at ZoneDelegate.invokeTask (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:423:38)

EditUser.spec.ts EditUser.spec.ts

import {EditUserAdmin} from "./EditUser.component";
import {
    it,
    inject,
    injectAsync,
    describe,
    beforeEachProviders,
    beforeEach,
    TestComponentBuilder,
    setBaseTestProviders,
    ComponentFixture,
    expect
} from 'angular2/testing';
import {provide} from 'angular2/core';
import { Component, OnInit,
    ROUTER_DIRECTIVES, RouteParams, Router,
    Http, HTTP_PROVIDERS, Headers,
    CRUDService,
    APIService } from '../index';
import {
    TEST_BROWSER_PLATFORM_PROVIDERS,
    TEST_BROWSER_APPLICATION_PROVIDERS
} from 'angular2/platform/testing/browser';
class MockApiService {
    getAPI() {
        return {
            TeamDrpList: "TrackerUser/GetUserCreateTeamMember",
            UserDrpList: "TrackerGroup/GetAllList"
        }
    }
}
class MockCRUD {
}
class MockRouter {
}
setBaseTestProviders(TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS);
describe('EditUserAdmin', () => {
    var app : EditUserAdmin;
    beforeEach(injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
        return tcb
            .overrideProviders(EditUserAdmin, [
                provide(CRUDService, { useClass: CRUDService }),
                provide(APIService, { useClass: MockApiService }),
                provide(RouteParams, { useValue: new RouteParams({ UserId: '1' }) }),
                provide(Router, { useClass: MockRouter })
            ])
            .createAsync(EditUserAdmin)
            .then((componentFixture: any) => {
                this.component = componentFixture;
            });
    }));    
    it('Change Event Method', () => {             
            app.changed("india");
              expect(app.selectControl).toEqual("india");           
    });
});

EditUser.ts EditUser.ts

import { Component, OnInit,
    ROUTER_DIRECTIVES, RouteParams, Router,
    Http, HTTP_PROVIDERS, Headers,
    CRUDService,
    APIService } from '../index';
import "rxjs/Rx";

@Component({
    templateUrl: 'app/Tracker/EditUserAdmin/EditUser.component.html',
    directives: [ROUTER_DIRECTIVES],
    providers: [HTTP_PROVIDERS, CRUDService, APIService]
})
export class EditUserAdmin implements OnInit {

    selectedCity: string;
    items: any[]; //select dropdown array
    teams: any[];
    GroupValue: any[] = [];
    TeamValue: any[] = [];
    optionAvailable: boolean = false;
    ProfileDetails: any;
    assignedGroup: any[];
    assignedTeam: any[];
    Get_APIService: any;
    GetUserurl: string;
    GroupUrl: string;
    GetUserID: string;
    selectControl: string; //Group Assignment Change event
    selectTeam: string;
    insertGroupId: any;
    QueryString: string;
    isBrokerHidden: boolean;
    ErrorMsg: string;
    SuccessMsg: string;

    constructor(private CRUDService: CRUDService, private APIService: APIService, params: RouteParams, private router: Router) {
        //To invoke Http service
        this.Get_APIService = this.APIService.getAPI();
        this.GetUserID = params.get("UserId");
        this.ProfileDetails = {
            LastName: "",
            FirstName: "",
            LoginName: "",
            Email: "",
            IsBrokerUser: false
        }
        this.QueryString = params.get("UserId");
        this.isBrokerHidden = true;
    }
    ngOnInit() {
        this.GroupUrl = this.Get_APIService.GetTrackerGroup + "?NewtrackeruserID=" + this.GetUserID;
        this.CRUDService.getServerData(this.Get_APIService.TeamDrpList + "?NewtrackeruserID=" + this.GetUserID, "")
            .subscribe(
            data => {
                this.teams = data.TeamMembersAvailable;
                // this.items = data.GroupAvailable;
                this.assignedTeam = data.TeamMembersAssigned.map(function (a) {
                    return { GroupName: a.DisplayName, AssignedId: a.UserID };
                });
                this.TeamValue.push.apply(this.TeamValue, this.assignedTeam);
            },
            error => this.CRUDService.logError(error)
            );
        this.CRUDService.getServerData(this.GroupUrl, "")
            .subscribe(
            data => {
                this.items = data.GroupAvailable;
                this.assignedGroup = data.GroupAssigned.map(function (a) {
                    return { GroupName: a.Name, AssignedId: a.GroupID };
                });
                this.GroupValue.push.apply(this.GroupValue, this.assignedGroup);
            },
            error => this.CRUDService.logError(error)
            );
        if (this.QueryString != "0") {
            this.GetUserurl = this.Get_APIService.GetUser + this.GetUserID;
            this.CRUDService.getServerData(this.GetUserurl, "")
                .subscribe(
                data => {
                    this.ProfileDetails = data;
                },
                error => this.CRUDService.logError(error)
                );
            setTimeout(() => {
                this.CRUDService.getServerData(this.Get_APIService.BrokoerUrl, "")
                    .subscribe(
                    data => {
                        if (this.GroupValue.length > 0) {
                            var Groupary = this.GroupValue.map(function (a) { return a.AssignedId; });
                            // this.ProfileDetails = data;
                            this.isBrokerHidden = !(Groupary.indexOf(data.GroupID) > -1);
                        }
                    },
                    error => this.CRUDService.logError(error)
                    );
            }, 100);
        }
    }
    //Select dropdown Change Event-IE 11 support
    changed(selectedValue: string) {
        this.selectControl = selectedValue;
    }
    ChangeTeam(value: string) {
        this.selectTeam = value;
    }
    //Event to add the Group
    addGroup(value) {
        var a, b;
        var selectedname: string;
        var selectedID: Number;
        let ind = this.items.map(function (obj, index) {
            if (obj.GroupID == value) {
                a = index;
                selectedname = obj.Name;
                selectedID = obj.GroupID;
                return a;
            }
        });
        if (a == "undefiened" || a == null) {
            alert("Select Group Assignment");
            return false;
        } else {
            this.GroupValue.push({ GroupName: selectedname, AssignedId: selectedID });
        }
        b = this.items.splice(a, 1);
        this.items.sort(function (x, y) {
            return (x.GroupID > y.GroupID) ? 1 : ((y.GroupID > x.GroupID) ? -1 : 0);
        });
    }
    addTeam(value) {
        var a, b;
        var selectedname: string;
        var selectedID: Number;
        let ind = this.teams.map(function (obj, index) {
            if (obj.UserID == value) {
                a = index;
                selectedname = obj.DisplayName;
                selectedID = obj.UserID;
                return a;
            }
        });
        if (value == "undefiened" || value == null) {
            alert("Select Team Member");
            return false;
        }
        else {
            var headers = new Headers();
            headers.append('Content-Type', 'application/json');
            this.CRUDService.postServerData(this.Get_APIService.AddTeamMember + "?Trackeruserid=" + this.GetUserID + "&newMemberID=" + value, "", headers)
                .subscribe(
                data => {
                    if (data == true) {
                        b = this.teams.splice(a, 1);
                        this.TeamValue.push({ GroupName: selectedname, AssignedId: selectedID });
                    }
                    else {

                    }
                },
                error => this.CRUDService.logError(error)
                );
            this.teams.sort(function (x, y) {
                return (x.UserID > y.UserID) ? 1 : ((y.UserID > x.UserID) ? -1 : 0);
            });
        }
    }
    //Event to unassign the Group
    unassignGroup(a: any) {
        var selectobject = <HTMLSelectElement>document.getElementById("group-select");
        for (var i = 0; i < selectobject.length; i++) {
            if ((<HTMLOptionElement>selectobject.options[i]).value == a.GroupName) {
                this.optionAvailable = true;
            }
        }
        if (this.optionAvailable == false) {
            this.items.push({
                Name: a.GroupName,
                GroupID: a.AssignedId
            });
            var index = this.GroupValue.indexOf(a);
            if (index > -1) {
                this.GroupValue.splice(index, 1);
                this.items.sort(function (a, b) {
                    return (a.GroupID > b.GroupID) ? 1 : ((b.GroupID > a.GroupID) ? -1 : 0);
                });
            }
        }
    }
    unassignTeam(a: any) {
        var selectobject = <HTMLSelectElement>document.getElementById("Team-select");
        for (var i = 0; i < selectobject.length; i++) {
            if ((<HTMLOptionElement>selectobject.options[i]).value == a.GroupName) {
                this.optionAvailable = true;
            }
        }
        if (this.optionAvailable == false) {
            var headers = new Headers();
            headers.append('Content-Type', 'application/json');
            this.CRUDService.postServerData(this.Get_APIService.RemoveTeamMember + "?Trackeruserid=" + this.GetUserID + "&teamMemberID=" + a.AssignedId, "", headers)
                .subscribe(
                data => {
                    if (data == true) {
                        // b = this.teams.splice(a, 1);
                        this.teams.push({
                            DisplayName: a.GroupName,
                            UserID: a.AssignedId
                        });
                    }
                    else {
                        // do nothing
                    }
                    var index = this.TeamValue.indexOf(a);
                    if (index > -1) {
                        this.TeamValue.splice(index, 1);
                        this.teams.sort(function (a, b) {
                            return (a.UserID > b.UserID) ? 1 : ((b.UserID > a.UserID) ? -1 : 0);
                        });
                    }
                },
                error => this.CRUDService.logError(error)
                );


        }
    }
    EditUser() {

        var headers = new Headers();
        if (this.QueryString != "0") {
            this.insertGroupId = this.GroupValue.map(function (a) { return a.AssignedId; });
            var creds: string = JSON.stringify({ LastName: this.ProfileDetails.LastName, FirstName: this.ProfileDetails.FirstName, LoginName: this.ProfileDetails.LoginName, Email: this.ProfileDetails.Email, IsBrokerUser: this.ProfileDetails.IsBrokerUser, GroupID: this.insertGroupId, UserID: this.GetUserID });

            headers.append('Content-Type', 'application/json');
            this.CRUDService.postServerData(this.Get_APIService.SaveUser, creds, headers)
                .subscribe(
                data => {
                    if (data == true) {
                        ///alert("User  Saved");
                        document.getElementById("ErrorStatus").style.display = "none";
                        document.getElementById("SucessStatus").style.display = "";
                        //document.getElementById("SucessStatus").innerHTML = "";
                        this.SuccessMsg = "Tracker User information was saved successfully.";
                        scrollTo(0, 0);

                    }
                    else {
                        // do nothing
                    }
                },
                error => {
                    if (error.status == 500) {
                        var errorMsg = JSON.parse(error._body);
                        //  alert();
                        document.getElementById("SucessStatus").style.display = "none";
                        document.getElementById("ErrorStatus").style.display = "";
                        //document.getElementById("ErrorStatus").innerHTML = "Tracker User information was saved successfully.";
                        this.ErrorMsg = errorMsg.ExceptionMessage;
                        scrollTo(0, 0);
                    }
                    this.CRUDService.logError(error);;
                }
                );
        }

        else {

            this.insertGroupId = this.GroupValue.map(function (a) { return a.AssignedId; });
            var creds: string = JSON.stringify({ LastName: this.ProfileDetails.LastName, FirstName: this.ProfileDetails.FirstName, LoginName: this.ProfileDetails.LoginName, Email: this.ProfileDetails.Email, IsBrokerUser: this.ProfileDetails.IsBrokerUser, GroupID: this.insertGroupId });
            headers.append('Content-Type', 'application/json');
            this.CRUDService.postServerData(this.Get_APIService.SaveUser, creds, headers)
                .subscribe(
                data => {
                    if (data == true) {
                        document.getElementById("ErrorStatus").style.display = "none";
                        document.getElementById("SucessStatus").style.display = "";
                        this.SuccessMsg = "Tracker User information was saved successfully.";
                        scrollTo(0, 0);
                    }
                    else {
                        // do nothing
                    }
                },
                error => {
                    if (error.status == 500) {
                        var errorMsg = JSON.parse(error._body);
                        document.getElementById("SucessStatus").style.display = "none";
                        document.getElementById("ErrorStatus").style.display = "";
                        this.ErrorMsg = errorMsg.ExceptionMessage;
                        scrollTo(0, 0);
                    }
                    this.CRUDService.logError(error);
                }
                );

        }
    }
    CancelEditUser() {
        this.router.navigate(['TrackerUserAdmin']);
    }


}

f.componentInstance gets all the methods properties to test my application using jasmine f.componentInstance获取使用jasmine测试我的应用程序的所有方法属性

  beforeEach(injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
            return tcb
                .overrideProviders(EditUserAdmin, [
                    provide(EditUserService, { useClass: EditUserMock }),
                    provide(APIServiceConstants, { useClass: APIServiceConstants }),
                    provide(RouteParams, { useValue: new RouteParams({ UserId: "48288" }) }),
                    provide(Router, { useClass: MockRouter })
                ])
                .createAsync(EditUserAdmin)
                .then((f) => {
                    f.detectChanges();
                    app = f.componentInstance;
                    fixture = f;
                });
        }));

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

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