在离子2单元测试中无法读取未定义的属性'_getPortal' [英] Cannot read property '_getPortal' of undefined in ionic 2 Unit testing

查看:241
本文介绍了在离子2单元测试中无法读取未定义的属性'_getPortal'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是离子2单元测试的初学者。我遵循了angular 2文档( https://angular.io/docs/ts/最新/指南/ testing.html )用业力和茉莉来测试我的离子2应用。

I am a beginner to ionic 2 unit testing. I followed angular 2 documentation (https://angular.io/docs/ts/latest/guide/testing.html) to test my ionic 2 application with karma and jasmine.

但是现在我陷入一个错误,叫做

But now I am stuck in an error called


'无法读取属性'_getPortal'未定义'

'Cannot read property '_getPortal' of undefined'

这是我的 LocationSearchModal.ts 文件

import { Component } from '@angular/core';
import { NavController, ViewController } from 'ionic-angular';
import { Location } from '../../services/domain/Location';
import { LocationService } from '../../services/LocationService';
import { LoadingController } from 'ionic-angular';

@Component({
  selector: 'location-search-modal',
  templateUrl: 'location-search-modal.html'
})
export class LocationSearchModal {
  locationList: Array<Location> = new Array<Location>();
  selectedLocation: number;
  temp: any = "test";

  constructor(public navCtrl: NavController, public locationService: LocationService, public viewController: ViewController, public loadingController: LoadingController) {
    this.filterLocationsForString();
  }

  filterLocations(event: any): void {
    const searchString: string = event.target.value;
    this.filterLocationsForString(searchString);
    console.log(this.filterLocationsForString(searchString));
  }

  filterLocationsForString(searchString?: string) {
    let loader = this.loadingController.create({
      content: "loading"
    });
    loader.present();
    this.locationService.getLocationsForLikeSearchString(searchString)
      .subscribe((result) => {
        loader.dismissAll();
        this.locationList = result
      });
    console.log(this.locationList);
  }

  closeLocationSearch() {
    this.locationService.getLocationById(this.selectedLocation)
      .subscribe((location) => this.viewController.dismiss(location[0]));
  }

}

我使用了名为locationService的服务。在那里,这就是那个服务

and I used service called locationService.ts there and this is that service

import { Injectable } from '@angular/core';
import { Location } from './domain/Location';

import { DatabaseAccessor } from  '../database/DatabaseAccessor';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class LocationService {
  locationList:Array<Location> = new Array<Location>();

  constructor(public databaseAccessor: DatabaseAccessor) {}

  getLocationsForLikeSearchString(searchString: string) : Observable<Array<Location>> {
    const searchValue = (searchString == null) ? '%' : searchString.trim() + '%';
    return <Observable<Array<Location>>> Observable.fromPromise(this.databaseAccessor.runSelectQuery(Location, new Location(), 'WHERE name LIKE ?', [searchValue]));
  }

  getLocationById(id: number): Observable<Location> {
    return <Observable<Location>> Observable.fromPromise(this.databaseAccessor.runSelectQuery(Location, new Location(), 'WHERE id = ?', [id]));
  }

  saveLocations(locations: Array<Location>){
    this.databaseAccessor.runInsertBatchQuery(Location.prototype, locations);
  }


}

最后,我写了一个 spec.ts 文件到单元测试,这就是,

Finally, I wrote a spec.ts file to unit testing and here is that,

import { ComponentFixture, async } from '@angular/core/testing';
import { LocationSearchModal } from './LocationSearchModal';
import { LocationService } from '../../services/LocationService';
import { TestUtils } from '../../test';
import { TestBed } from '@angular/core/testing';
import { App, NavController, Platform, Config, Keyboard, Form, IonicModule, GestureController, ViewController, LoadingController }  from 'ionic-angular';
import { ConfigMock } from '../../mocks';
import { TranslateModule } from 'ng2-translate';
import { DatabaseAccessor } from  '../../database/DatabaseAccessor';

let comp: LocationSearchModal;
let fixture: ComponentFixture<LocationSearchModal>;
let instance: any = null;

describe('LocationSearchModal', () => {

  beforeEach(async(() => {

    TestBed.configureTestingModule({
      declarations: [LocationSearchModal], // declare the test component
      providers: [App, Platform, Form, Keyboard, NavController, GestureController, LoadingController, LocationService, DatabaseAccessor,
        { provide: ViewController, useClass: class { ViewController = jasmine.createSpy("viewController"); } },
        { provide: Config, useClass: ConfigMock },
      ],
      imports: [
        IonicModule,
        TranslateModule.forRoot(),
      ],
    });
    fixture = TestBed.createComponent(LocationSearchModal);
    comp = fixture.componentInstance;
  }));

  console.log(comp);
  it('Testing Location Component', () => {
    expect(comp.temp).toBe('test');
  })
});

当我运行以下错误来自终端时。
(我的单元测试配置是正确的,我用另一个简单的.spec.ts文件测试它)

when I am running the following error comes from the terminal. (my unit testing configuration are correct and I tested it with another simple .spec.ts file)


错误

the error



SUMMARY:
✔ 1 test completed
✖ 1 test failed

FAILED TESTS:
  LocationSearchModal
    ✖ Testing Location Component
      Chrome 54.0.2840 (Linux 0.0.0)
    Failed: Error in ./LocationSearchModal class LocationSearchModal_Host - inline template:0:0 caused by: Cannot read property '_getPortal' of undefined
    TypeError: Cannot read property '_getPortal' of undefined
        at App.present (webpack:/media/dilanka/Stuff/CODE%20BASE/Inspection/Unit%20Testing/Inspection-Rewrite/~/ionic-angular/components/app/app.js:78:0 <- src/test.ts:2091:35)
        at Loading.present (webpack:/media/dilanka/Stuff/CODE%20BASE/Inspection/Unit%20Testing/Inspection-Rewrite/~/ionic-angular/components/loading/loading.js:31:0 <- src/test.ts:38779:26)
        at LocationSearchModal.filterLocationsForString (webpack:/media/dilanka/Stuff/CODE%20BASE/Inspection/Unit%20Testing/Inspection-Rewrite/src/pages/location-search/LocationSearchModal.ts:9:4184 <- src/test.ts:18993:4170)
        at new LocationSearchModal (webpack:/media/dilanka/Stuff/CODE%20BASE/Inspection/Unit%20Testing/Inspection-Rewrite/src/pages/location-search/LocationSearchModal.ts:9:3407 <- src/test.ts:18993:3391)
        at new Wrapper_LocationSearchModal (/DynamicTestModule/LocationSearchModal/wrapper.ngfactory.js:7:18)
        at _View_LocationSearchModal_Host0.createInternal (/DynamicTestModule/LocationSearchModal/host.ngfactory.js:16:35)
        at _View_LocationSearchModal_Host0.AppView.create (webpack:/media/dilanka/Stuff/CODE%20BASE/Inspection/Unit%20Testing/Inspection-Rewrite/~/@angular/core/src/linker/view.js:84:0 <- src/test.ts:52350:21)
        at _View_LocationSearchModal_Host0.DebugAppView.create (webpack:/media/dilanka/Stuff/CODE%20BASE/Inspection/Unit%20Testing/Inspection-Rewrite/~/@angular/core/src/linker/view.js:294:0 <- src/test.ts:52560:44)
        at ComponentFactory.create (webpack:/media/dilanka/Stuff/CODE%20BASE/Inspection/Unit%20Testing/Inspection-Rewrite/~/@angular/core/src/linker/component_factory.js:152:0 <- src/test.ts:32035:36)
        at initComponent (webpack:/media/dilanka/Stuff/CODE%20BASE/Inspection/Unit%20Testing/Inspection-Rewrite/~/@angular/core/bundles/core-testing.umd.js:855:0 <- src/test.ts:7416:53)


推荐答案

我终于解决了这个问题。我在mock中使用了mock和定义的必需方法。然后它工作:)

这里是一个模拟的例子。

I Solved this problem finally. I used a mock and defined required methods in that mock. Then It works :)
here is an example for a mock.

export class ViewControllerMock {
  public _setHeader(): any { return {} };
  public _setNavbar(): any { return {} };
  public _setIONContent(): any { return {} };
  public _setIONContentRef(): any { return {} };
}

然后必须将该模拟导入 .spec .ts 文件如下

then have to import that mock into your .spec.ts file as follows

import {ViewControllerMock} from '../../mocks';

然后必须在 spec.ts中定义您的提供商中的模拟文件如下

providers: [{ provide: ViewController, useClass: ViewControllerMock}],

这篇关于在离子2单元测试中无法读取未定义的属性'_getPortal'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆