Base solution for your next web application
Open Closed

Need help with Angular 5 unit testing with jasmine #5297


User avatar
0
sumitshah created

Using the aspnetzero RAD tools we have created a component and its back-end services. The functionality is working as desired. Now we are trying to write unit tests in jasmine for this particular component. For this we have created a new spec.ts file and import all the required dependencies. We need to create mock service to bind mock data on page load.

We followed a few of the posts mentioned below of how to mock the back end services: <a class="postlink" href="https://codecraft.tv/courses/angular/unit-testing/mocks-and-spies/">https://codecraft.tv/courses/angular/un ... and-spies/</a> <a class="postlink" href="https://alligator.io/angular/testing-with-spies/">https://alligator.io/angular/testing-with-spies/</a>

We are facing issue creating the mock service and consuming the same in the describe function. Below is the component.ts code

import { Component, Injector, ViewEncapsulation, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Http } from '@angular/http';
import { DatabasesServiceProxy, DatabaseDto  } from '@shared/service-proxies/service-proxies';
import { NotifyService } from '@abp/notify/notify.service';
import { AppComponentBase } from '@shared/common/app-component-base';
import { TokenAuthServiceProxy } from '@shared/service-proxies/service-proxies';
import { CreateOrEditDatabaseModalComponent } from './create-or-edit-database-modal.component';
import { ViewDatabaseModalComponent } from './view-database-modal.component';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { DataTable } from 'primeng/components/datatable/datatable';
import { Paginator } from 'primeng/components/paginator/paginator';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { FileDownloadService } from '@shared/utils/file-download.service';
import * as moment from 'moment';

@Component({
    templateUrl: './databases.component.html',
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class DatabasesComponent extends AppComponentBase {

    @ViewChild('createOrEditDatabaseModal') createOrEditDatabaseModal: CreateOrEditDatabaseModalComponent;
    @ViewChild('viewDatabaseModalComponent') viewDatabaseModal: ViewDatabaseModalComponent;
    @ViewChild('dataTable') dataTable: DataTable;
    @ViewChild('paginator') paginator: Paginator;
	
    advancedFiltersAreShown = false;
	filterText = '';
		lK_DatabaseTypeFilter = '';
		cDatabaseNameFilter = '';
		cListFileUploadedPathFilter = '';
		cListReadyToLoadPathFilter = '';
		maxdCreatedDateFilter : moment.Moment;
		mindCreatedDateFilter : moment.Moment;
		cCreatedByFilter = '';
		maxdModifiedDateFilter : moment.Moment;
		mindModifiedDateFilter : moment.Moment;
		cModifiedByFilter = '';
		lK_AccountingDivisionCodeFilter = '';
		cAdministrationEmailFilter = '';
		divisioncDivisionNameFilter = '';

	

    constructor(
        injector: Injector,
        private _http: Http,
        private _databasesServiceProxy: DatabasesServiceProxy,
        private _notifyService: NotifyService,
        private _tokenAuth: TokenAuthServiceProxy,
        private _activatedRoute: ActivatedRoute,
        private _fileDownloadService: FileDownloadService
    )
    {
        super(injector);
    }

    getDatabases(event?: LazyLoadEvent) {
        if (this.primengDatatableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);
            return;
        }

        this.primengDatatableHelper.showLoadingIndicator();

        this._databasesServiceProxy.getAll(
			this.filterText,
			this.lK_DatabaseTypeFilter,
			this.cDatabaseNameFilter,
			this.cListFileUploadedPathFilter,
			this.cListReadyToLoadPathFilter,
			this.maxdCreatedDateFilter,
			this.mindCreatedDateFilter,
			this.cCreatedByFilter,
			this.maxdModifiedDateFilter,
			this.mindModifiedDateFilter,
			this.cModifiedByFilter,
			this.lK_AccountingDivisionCodeFilter,
			this.cAdministrationEmailFilter,
            this.cAdministrationEmailFilter,
            null,
            this.primengDatatableHelper.getSorting(this.dataTable),
            this.primengDatatableHelper.getSkipCount(this.paginator, event),
            this.primengDatatableHelper.getMaxResultCount(this.paginator, event)
        ).subscribe(result => {
            this.primengDatatableHelper.totalRecordsCount = result.totalCount;
            this.primengDatatableHelper.records = result.items;
            this.primengDatatableHelper.hideLoadingIndicator();
        });
    }

    reloadPage(): void {
        this.paginator.changePage(this.paginator.getPage());
    }

    createDatabase(): void {
        this.createOrEditDatabaseModal.show();
    }

    deleteDatabase(database: DatabaseDto): void {
        this.message.confirm(
            '',
            (isConfirmed) => {
                if (isConfirmed) {
                    this._databasesServiceProxy.delete(database.id)
                        .subscribe(() => {
                            this.reloadPage();
                            this.notify.success(this.l('SuccessfullyDeleted'));
                        });
                }
            }
        );
    }

	exportToExcel(): void {
        this._databasesServiceProxy.getDatabasesToExcel(
		this.filterText,
			this.lK_DatabaseTypeFilter,
			this.cDatabaseNameFilter,
			this.cListFileUploadedPathFilter,
			this.cListReadyToLoadPathFilter,
			this.maxdCreatedDateFilter,
			this.mindCreatedDateFilter,
			this.cCreatedByFilter,
			this.maxdModifiedDateFilter,
			this.mindModifiedDateFilter,
			this.cModifiedByFilter,
			this.lK_AccountingDivisionCodeFilter,
			this.cAdministrationEmailFilter,
			this.divisioncDivisionNameFilter,
		)
        .subscribe(result => {
            this._fileDownloadService.downloadTempFile(result);
         });
    }
}

could you please help us on this.


3 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    What is the problem you are facing, could you explain ?

  • User Avatar
    0
    sumitshah created

    Thank you!!

    So have already attached the component.ts file code with this post. I want to write unit test in jasmine for this component. The component has a getDatabases method which calls a service getAll. I need to mock this service and create some basic specs in jamine.

    Have tried below code for writing the specs.ts file:

    /// <reference path="D:/Development/IDMS_vNext/IDMS/src/Infogroup.IDMS.Web.Host/node_modules/@types/jasmine/index.d.ts" />
    import { TestBed, async, ComponentFixture, ComponentFixtureAutoDetect } from '@angular/core/testing';
    import { BrowserModule, By } from "@angular/platform-browser";
    import { NgModule, Injector, DebugElement } from '@angular/core';
    import { CommonModule, DeprecatedI18NPipesModule } from '@angular/common';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    import { DatabasesComponent } from './databases.component';
    import { ViewDatabaseModalComponent } from './view-database-modal.component';
    import { CreateOrEditDatabaseModalComponent } from './create-or-edit-database-modal.component';
    import { DivisionLookupTableModalComponent } from './division-lookup-table-modal.component';
    import { DivisionsComponent } from '../../divisions/divisions/divisions.component';
    import { ViewDivisionModalComponent } from '../../divisions/divisions/view-division-modal.component';
    import { CreateOrEditDivisionModalComponent } from '../../divisions/divisions/create-or-edit-division-modal.component';
    import { DataTableModule } from 'primeng/primeng';
    import { FileUploadModule } from 'primeng/primeng';
    import { AutoCompleteModule } from 'primeng/primeng';
    import { PaginatorModule } from 'primeng/primeng';
    import { EditorModule } from 'primeng/primeng';
    import { InputMaskModule } from 'primeng/primeng';
    import { ModalModule, TabsModule, TooltipModule } from 'ngx-bootstrap';
    import { AppCommonModule } from '@app/shared/common/app-common.module';
    import { UtilsModule } from '@shared/utils/utils.module';
    import { MaintenanceRoutingModule } from '../../maintenance-routing.module';
    import { CountoModule } from 'angular2-counto';
    import { EasyPieChartModule } from 'ng2modules-easypiechart';
    import { DropdownModule } from 'primeng/dropdown';
    import { KendoDivisionsComponent } from '@app/maintenance/KendoUI/divisions/divisions.component';
    import { KendoCreateOrEditDivisionModalComponent } from '@app/maintenance/KendoUI/divisions/create-or-edit-division-modal.component';
    import { KendoViewDivisionModalComponent } from '@app/maintenance/KendoUI/divisions/view-division-modal.component';
    import { GridModule } from '@progress/kendo-angular-grid';
    import { KendoCreateOrEditDatabaseModalComponent } from '@app/maintenance/KendoUI/databases/databases/create-or-edit-database-modal.component';
    import { KendoDivisionLookupTableModalComponent } from '@app/maintenance/KendoUI/databases/databases/division-lookup-table-modal.component';
    import { KendoDatabasesComponent } from '@app/maintenance/KendoUI/databases/databases/databases.component';
    import { KendoViewDatabaseModalComponent } from '@app/maintenance/KendoUI/databases/databases/view-database-modal.component';
    import { CampaignsComponent } from '@app/maintenance/campaigns/campaigns/campaigns.component';
    import { BuildsComponent } from '@app/maintenance/prime-ngTurbo-table/builds/builds/builds.component';
    import { ViewBuildModalComponent } from '@app/maintenance/prime-ngTurbo-table/builds/builds/view-build-modal.component';
    import { CreateOrEditBuildModalComponent } from '@app/maintenance/prime-ngTurbo-table/builds/builds/create-or-edit-build-modal.component';
    import { ChildDatabaseComponent } from '@app/maintenance/prime-ng/child-database/child-database.component';
    import { PrimeNGComponent } from '@app/maintenance/prime-ng/prime-ng/prime-ng.component';
    import { TurboComponent } from '@app/maintenance/prime-ngTurbo-table/databases//databases/prime-ngTurbo-table.component';
    import { TableModule } from 'primeng/table';
    import { SegmentsComponent } from '../../campaigns/segments/segments.component';
    import { CreateOrEditCampaignModalComponent } from '../../campaigns/campaigns/create-or-edit-campaign-modal.component';
    import { CreateOrEditSegmentModalComponent } from '@app/maintenance/campaigns/Segments/create-or-edit-segment-modal.component';
    import { HttpModule, JsonpModule, Http } from '@angular/http';
    import { DatabasesServiceProxy, TokenAuthServiceProxy, LookupsServiceProxy, SessionServiceProxy, PagedResultDtoOfGetDatabaseForView } from '@shared/service-proxies/service-proxies';
    import { RouterTestingModule } from "@angular/router/testing";
    import { AppSessionService } from '@shared/common/session/app-session.service';
    import { AppUiCustomizationService } from '@shared/common/ui/app-ui-customization.service';
    import { LinkedAccountService } from '@app/shared/layout/linked-account.service';
    import { AppUrlService } from '@shared/common/nav/app-url.service';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { Observable } from 'rxjs/Rx';
    import 'rxjs/add/observable/of';
    import * as moment from 'moment';
    import { NotifyService } from 'abp-ng2-module/src/notify/notify.service';
    import { ActivatedRoute } from '@angular/router';
    import { FileDownloadService } from '@shared/utils/file-download.service';
    let component: DatabasesComponent;
    let fixture: ComponentFixture<DatabasesComponent>;
    
    class MockDatabasesService {
        result: { totalcount: number,items: any; };
        public results: Array<any>;
        public getAll(
            filterText?: string,
            lK_DatabaseTypeFilter?: string,
            cDatabaseNameFilter?: string,
            cListFileUploadedPathFilter?: string,
            cListReadyToLoadPathFilter?: string,        
            maxdCreatedDateFilter?: moment.Moment,
            mindCreatedDateFilter?: moment.Moment,
            cCreatedByFilter?: string,
            maxdModifiedDateFilter?: moment.Moment,
            mindModifiedDateFilter?: moment.Moment,
            cModifiedByFilter?: string,
            lK_AccountingDivisionCodeFilter?: string,
            cAdministrationEmailFilter?: string,
            divisionDivisionIdFilter?:string,
            sorting?: string,
            skipCount?: string,
            maxResultCount?: number
        ) {
            this.result = {
                totalcount:1209,
                items:[
                    {
                        "database": {
                            "lK_DatabaseType": "U",
                            "cDatabaseName": "US Data Warehouse11",
                            "cListFileUploadedPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\DDI_Upload\\ReadyToLoadFiles\\",
                            "cListReadyToLoadPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\DDI_Upload\\ReadyToLoadFiles\\",
                            "dCreatedDate": "2009-08-03T05:25:10.963",
                            "cCreatedBy": "admin1",
                            "dModifiedDate": "2015-01-19T03:53:26.337",
                            "cModifiedBy": "test.test",
                            "lK_AccountingDivisionCode": "559000",
                            "cAdministratorEmail": "[email protected]",
                            "divisionId": 181,
                            "id": 65
                        },
                        "divisioncDivisionName": "Walter Karl"
                    },
                    {
                        "database": {
                            "lK_DatabaseType": "C",
                            "cDatabaseName": "Canadian Data Warehouse",
                            "cListFileUploadedPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\DDI_Upload\\ReadyToLoadFiles\\",
                            "cListReadyToLoadPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\DDI_Upload\\ReadyToLoadFiles\\",
                            "dCreatedDate": "2009-08-06T16:32:14.533",
                            "cCreatedBy": "admin1",
                            "dModifiedDate": "2015-01-22T14:23:46.133",
                            "cModifiedBy": "test.test",
                            "lK_AccountingDivisionCode": "559000",
                            "cAdministratorEmail": "[email protected]",
                            "divisionId": 177,
                            "id": 66
                        },
                        "divisioncDivisionName": "Infogroup - ITS"
                    },
                    {
                        "database": {
                            "lK_DatabaseType": "U",
                            "cDatabaseName": "Pitney Bowes - Private DB",
                            "cListFileUploadedPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\List_Owner_Upload\\SourceFiles\\",
                            "cListReadyToLoadPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\DDI_Upload\\ReadyToLoadFiles\\",
                            "dCreatedDate": "2009-08-06T15:55:10.963",
                            "cCreatedBy": "admin1",
                            "dModifiedDate": "2017-08-16T21:35:43.967",
                            "cModifiedBy": "test.test",
                            "lK_AccountingDivisionCode": "559000",
                            "cAdministratorEmail": "[email protected]",
                            "divisionId": 187,
                            "id": 68
                        },
                        "divisioncDivisionName": "Division for Inactive-Old Database"
                    },
                    {
                        "database": {
                            "lK_DatabaseType": "U",
                            "cDatabaseName": "Jameson - OLD",
                            "cListFileUploadedPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\List_Owner_Upload\\SourceFiles\\",
                            "cListReadyToLoadPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\DDI_Upload\\ReadyToLoadFiles\\",
                            "dCreatedDate": "2011-06-23T07:26:46.72",
                            "cCreatedBy": "test.test",
                            "dModifiedDate": "2017-08-16T21:35:43.967",
                            "cModifiedBy": "test.test",
                            "lK_AccountingDivisionCode": "999999",
                            "cAdministratorEmail": "[email protected]",
                            "divisionId": 187,
                            "id": 69
                        },
                        "divisioncDivisionName": "Division for Inactive-Old Database"
                    },
                    {
                        "database": {
                            "lK_DatabaseType": "U",
                            "cDatabaseName": "BNP Media - ePost DB",
                            "cListFileUploadedPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\List_Owner_Upload\\SourceFiles\\",
                            "cListReadyToLoadPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\DDI_Upload\\ReadyToLoadFiles\\",
                            "dCreatedDate": "2011-07-19T14:21:17.547",
                            "cCreatedBy": "test.test",
                            "dModifiedDate": "2017-08-16T21:35:43.967",
                            "cModifiedBy": "test.test",
                            "lK_AccountingDivisionCode": "999999",
                            "cAdministratorEmail": "[email protected]",
                            "divisionId": 187,
                            "id": 70
                        },
                        "divisioncDivisionName": "Division for Inactive-Old Database"
                    },
                    {
                        "database": {
                            "lK_DatabaseType": "U",
                            "cDatabaseName": "Sapphire",
                            "cListFileUploadedPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\DDI_Upload\\ReadyToLoadFiles\\",
                            "cListReadyToLoadPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\DDI_Upload\\ReadyToLoadFiles\\",
                            "dCreatedDate": "2011-09-14T11:21:44.967",
                            "cCreatedBy": "test.test",
                            "dModifiedDate": "2014-05-18T11:48:09.763",
                            "cModifiedBy": "test.test",
                            "lK_AccountingDivisionCode": "559000",
                            "cAdministratorEmail": "[email protected]",
                            "divisionId": 188,
                            "id": 71
                        },
                        "divisioncDivisionName": "Infogroup"
                    },
                    {
                        "database": {
                            "lK_DatabaseType": "U",
                            "cDatabaseName": "Interactive Reporting",
                            "cListFileUploadedPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\List_Owner_Upload\\SourceFiles\\",
                            "cListReadyToLoadPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\DDI_Upload\\ReadyToLoadFiles\\",
                            "dCreatedDate": "2011-12-16T13:20:33.303",
                            "cCreatedBy": "test.test",
                            "dModifiedDate": "2017-08-16T21:35:43.967",
                            "cModifiedBy": "test.test",
                            "lK_AccountingDivisionCode": "000000",
                            "cAdministratorEmail": "[email protected]",
                            "divisionId": 187,
                            "id": 72
                        },
                        "divisioncDivisionName": "Division for Inactive-Old Database"
                    },
                    {
                        "database": {
                            "lK_DatabaseType": "U",
                            "cDatabaseName": "Advanstar",
                            "cListFileUploadedPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\List_Owner_Upload\\SourceFiles\\",
                            "cListReadyToLoadPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\DDI_Upload\\ReadyToLoadFiles\\",
                            "dCreatedDate": "2012-01-09T18:02:43.223",
                            "cCreatedBy": "test.test",
                            "dModifiedDate": "2017-08-16T21:35:43.967",
                            "cModifiedBy": "test.test",
                            "lK_AccountingDivisionCode": "999999",
                            "cAdministratorEmail": "[email protected]",
                            "divisionId": 187,
                            "id": 73
                        },
                        "divisioncDivisionName": "Division for Inactive-Old Database"
                    },
                    {
                        "database": {
                            "lK_DatabaseType": "U",
                            "cDatabaseName": "Apogee for Converts Only",
                            "cListFileUploadedPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\DDI_Upload\\ReadyToLoadFiles\\",
                            "cListReadyToLoadPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\DDI_Upload\\ReadyToLoadFiles\\",
                            "dCreatedDate": "2012-02-15T14:22:28.47",
                            "cCreatedBy": "test.test",
                            "dModifiedDate": "2012-07-15T18:31:52.137",
                            "cModifiedBy": "test.test",
                            "lK_AccountingDivisionCode": "506000",
                            "cAdministratorEmail": "[email protected]",
                            "divisionId": 177,
                            "id": 74
                        },
                        "divisioncDivisionName": "Infogroup - ITS"
                    },
                    {
                        "database": {
                            "lK_DatabaseType": "U",
                            "cDatabaseName": "CORP Base",
                            "cListFileUploadedPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\DDI_Upload\\ReadyToLoadFiles\\",
                            "cListReadyToLoadPath": "\\\\intra.infousa.com\\prl\\IDMSDevTest\\DDI_Upload\\ReadyToLoadFiles\\",
                            "dCreatedDate": "2012-03-05T10:59:18.713",
                            "cCreatedBy": "test.test",
                            "dModifiedDate": "2012-04-05T16:41:09.82",
                            "cModifiedBy": "test.test",
                            "lK_AccountingDivisionCode": "559000",
                            "cAdministratorEmail": "[email protected]",
                            "divisionId": 177,
                            "id": 75
                        },
                        "divisioncDivisionName": "Infogroup - ITS"
                    }
                ]
            }
    
            //return Observable.of(this.items);
            return Observable.of<PagedResultDtoOfGetDatabaseForView>(<any>null);
        }
    }
    
    describe('Databases Component', () => {
        let fixture: ComponentFixture<DatabasesComponent>;
        let debugElement: DebugElement;
        let databasesService: MockDatabasesService;
        let incrementSpy;
    
        beforeEach(async(() => {
                    TestBed.configureTestingModule({
                imports: [
                    ReactiveFormsModule,
                    BrowserModule, FormsModule, DataTableModule, BrowserAnimationsModule,
                    DropdownModule,
                    FileUploadModule,
                    AutoCompleteModule,
                    PaginatorModule,
                    EditorModule,
                    InputMaskModule,
                    CommonModule,
                    FormsModule,
                    ModalModule,
                    TabsModule,
                    TooltipModule,
                    AppCommonModule,
                    UtilsModule,
                    MaintenanceRoutingModule,
                    CountoModule,
                    EasyPieChartModule,
                    GridModule,
                    TableModule,
                    HttpModule,
                    RouterTestingModule.withRoutes([
                        {
                            path: '',
                            children: [
                                { path: 'databases/databases', component: DatabasesComponent, data: { permission: 'Pages.Databases' } }
    
                            ]
                        }
                    ]),
                ],
                declarations: [
                    DatabasesComponent,
                    ViewDatabaseModalComponent,
                    CreateOrEditDatabaseModalComponent,
                    DivisionLookupTableModalComponent,
                    DivisionsComponent,
                    ViewDivisionModalComponent,
                    CreateOrEditDivisionModalComponent,
                    KendoDivisionsComponent,
                    KendoCreateOrEditDivisionModalComponent,
                    KendoViewDivisionModalComponent,
                    KendoCreateOrEditDatabaseModalComponent,
                    KendoDivisionLookupTableModalComponent,
                    KendoDatabasesComponent,
                    KendoViewDatabaseModalComponent,
                    CampaignsComponent,
                    BuildsComponent,
                    ViewBuildModalComponent,
                    CreateOrEditBuildModalComponent,
                    ChildDatabaseComponent,
                    PrimeNGComponent,
                    TurboComponent,
                    SegmentsComponent,
                    CreateOrEditCampaignModalComponent,
                    CreateOrEditSegmentModalComponent
                ],
                providers: [
                    { provide: ComponentFixtureAutoDetect, useValue: true },
                    DatabasesServiceProxy,
                    TokenAuthServiceProxy,
                    AppSessionService,
                    SessionServiceProxy,
                    AppUiCustomizationService,
                    LinkedAccountService,
                    AppUrlService,
                    LookupsServiceProxy
                        ]
                    }).compileComponents();
    
            fixture = TestBed.createComponent(DatabasesComponent);
            debugElement = fixture.debugElement;
    
            databasesService = debugElement.injector.get(DatabasesServiceProxy);
            incrementSpy = spyOn(databasesService, 'getAll').and.callThrough();
        }));
    
        //it('should call increment on the service', () => {
        //    debugElement
        //        .query(By.css('button.increment'))
        //        .triggerEventHandler('click', null);
    
        //    expect(incrementDecrementService.value).toBe(1);
        //    expect(incrementSpy).toHaveBeenCalled();
        //});
    
        it('should have a defined component', () => {
            expect(component).toBeDefined();
        });
    });
    
    
    
    //describe('Component: Login', () => {
    
    //    let component: DatabasesComponent;
    //    let service: MockDatabasesService;
    
    //    beforeEach(() => {
    //        
    //    });
    
    //    afterEach(() => {
    //        service = null;
    //        component = null;
    //    });
    
    
    //    //it('canLogin returns false when the user is not authenticated', () => {
    //    //    service.authenticated = false;
    //    //    expect(component.needsLogin()).toBeTruthy();
    //    //});
    
    //    //it('canLogin returns false when the user is not authenticated', () => {
    //    //    service.authenticated = true;
    //    //    expect(component.needsLogin()).toBeFalsy();
    //    //});
    //});
    
    
    //describe('Databases Componentt', () => {
    //    let fixture: ComponentFixture<DatabasesComponent>;
    //    let itemService: MockDatabasesService;
    
    //    describe('Async', () => {
    //        beforeEach(async(() => {
    //            TestBed.configureTestingModule({
    //                declarations: [
    //                    ItemListComponent
    //                ],
    //                providers: [
    //                    //ItemService
    //                    { provide: ItemService, useClass: MockMyService }
    //                ],
    //                imports: [
    //                    GridModule, HttpModule
    //                ],
    //                schemas: [CUSTOM_ELEMENTS_SCHEMA]
    //            });
    
    //            fixture = TestBed.createComponent(ItemListComponent);
    //            itemService = fixture.debugElement.injector.get(ItemService);
    
    //            spyOn(itemService, 'getLatest')
    //                .and.returnValue({ subscribe: () => { itemService.items } });
    
    //            fixture.detectChanges();
    
    //        }));
    
    //        afterEach(() => {
    //            fixture = undefined;//teardown
    //        });
    
    //        it('should get items', () => {
    //            itemService.getLatest();
    //            expect(fixture.debugElement.componentInstance.items.length).toEqual(1);
    //        });
    
    //    });
    //});
    
    
    
    ////describe('Database component', () => {
    ////    beforeEach(async(() => {
    ////        TestBed.configureTestingModule({
    ////            imports: [
    ////                ReactiveFormsModule,
    ////                BrowserModule, FormsModule, DataTableModule, BrowserAnimationsModule,
    ////                DropdownModule,
    ////                FileUploadModule,
    ////                AutoCompleteModule,
    ////                PaginatorModule,
    ////                EditorModule,
    ////                InputMaskModule,
    ////                CommonModule,
    ////                FormsModule,
    ////                ModalModule,
    ////                TabsModule,
    ////                TooltipModule,
    ////                AppCommonModule,
    ////                UtilsModule,
    ////                MaintenanceRoutingModule,
    ////                CountoModule,
    ////                EasyPieChartModule,
    ////                GridModule,
    ////                TableModule,
    ////                HttpModule,
    ////                RouterTestingModule.withRoutes([
    ////                    {
    ////                        path: '',
    ////                        children: [
    ////                            { path: 'databases/databases', component: DatabasesComponent, data: { permission: 'Pages.Databases' } }
    
    ////                        ]
    ////                    }
    ////                ]),
    ////            ],
    ////            declarations: [
    ////                DatabasesComponent,
    ////                ViewDatabaseModalComponent,
    ////                CreateOrEditDatabaseModalComponent,
    ////                DivisionLookupTableModalComponent,
    ////                DivisionsComponent,
    ////                ViewDivisionModalComponent,
    ////                CreateOrEditDivisionModalComponent,
    ////                KendoDivisionsComponent,
    ////                KendoCreateOrEditDivisionModalComponent,
    ////                KendoViewDivisionModalComponent,
    ////                KendoCreateOrEditDatabaseModalComponent,
    ////                KendoDivisionLookupTableModalComponent,
    ////                KendoDatabasesComponent,
    ////                KendoViewDatabaseModalComponent,
    ////                CampaignsComponent,
    ////                BuildsComponent,
    ////                ViewBuildModalComponent,
    ////                CreateOrEditBuildModalComponent,
    ////                ChildDatabaseComponent,
    ////                PrimeNGComponent,
    ////                TurboComponent,
    ////                SegmentsComponent,
    ////                CreateOrEditCampaignModalComponent,
    ////                CreateOrEditSegmentModalComponent
    ////            ],
    ////            providers: [
    ////                { provide: ComponentFixtureAutoDetect, useValue: true },
    ////                DatabasesServiceProxy,
    ////                TokenAuthServiceProxy,
    ////                AppSessionService,
    ////                SessionServiceProxy,
    ////                AppUiCustomizationService,
    ////                LinkedAccountService,
    ////                AppUrlService,
    ////                LookupsServiceProxy
    ////            ]
    ////        });
    ////        fixture = TestBed.createComponent(DatabasesComponent);
    ////        component = fixture.componentInstance;
    ////    }));
    
        //it('should do something', async(() => {
        //    expect(true).toEqual(true);
        //}));
    
        //it('should return hello world', () => {
        //    const result = "Hello world!";
        //    expect(result).toEqual('Hello world!');
        //});
    
        //it('should have a defined component', () => {
        //    expect(component).toBeDefined();
        //});
    //});
    

    Not sure how can we mock a parameter service.

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    I haven't done this before but you can try <a class="postlink" href="https://alligator.io/angular/testing-with-spies/">https://alligator.io/angular/testing-with-spies/</a>