mIve得到了以下单元测试,测试了我用Ionic 2编写的组件。单元测试给出了Ionic库中的一个错误,我假设我没有正确地模拟它或作为Ionic 2 ViewController单元测试
import { ComponentFixture, async } from '@angular/core/testing';
import { TestUtils } from '../../test';
import {} from 'jasmine';
import { LocationSearchModal } from './LocationSearchModal';
import { LocationService } from '../../services/LocationService';
import { PouchDbService } from '../../services/common/PouchDbService';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { TestBed } from '@angular/core/testing';
import { App, MenuController, NavController, Platform, Config, Keyboard, Form, IonicModule, ViewController, GestureController, NavParams } from 'ionic-angular';
import { ConfigMock } from '../../mocks';
import { TranslateModule } from 'ng2-translate';
import { LoadingController } from 'ionic-angular';
let fixture: ComponentFixture<LocationSearchModal> = null;
let instance: any = null;
describe('LocationSearchModal',() => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
LocationSearchModal
],
providers: [
App, Platform, Form, Keyboard, MenuController, NavController, GestureController, LocationService, LoadingController,
{ provide: ViewController, useClass: class { ViewController = jasmine.createSpy("viewController"); } },
{ provide: NavParams, useClass: class { NavParams = jasmine.createSpy("navParams"); } },
{ provide: PouchDbService, useClass: class { PouchDbService = jasmine.createSpy("pouchDbService"); } },
{provide: Config, useClass: ConfigMock}
],
imports: [
FormsModule,
IonicModule,
ReactiveFormsModule,
TranslateModule.forRoot(),
],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(LocationSearchModal);
instance = fixture.debugElement.componentInstance;
fixture.autoDetectChanges(true);
});
}));
afterEach(() => {
fixture.destroy();
});
it('loads',() => {
expect(fixture).not.toBeNull();
expect(instance).not.toBeNull();
})
})
这是使用正在测试的组件的ViewController的相关摘录。
this.locationService.getLocationById(this.selectedLocation)
.subscribe((location: any) => {
this.viewController.dismiss(location.doc)
});
测试失败,我得到了下面的堆栈跟踪
Chrome 53.0.2785 (Linux 0.0.0)
TypeError: viewCtrl._setHeader is not a function
at new Header (webpack:///home/milinda/workspaces/eclipse/inspection/addedinspection/Inspection-Upgrade/~/ionic-angular/components/toolbar/toolbar.js:14:0 <- src/test.ts:11833:30)
at new Wrapper_Header (/IonicModule/Header/wrapper.ngfactory.js:7:18)
这关系到我已经创建了一个茉莉花间谍为
{ provide: ViewController, useClass: class { ViewController = jasmine.createSpy("viewController"); } },
有后ViewController
线看看代码库我在这里找到了_setHeader方法
我也试过编写自定义提供程序,但也得到了相同的错误。任何关于什么是测试ViewController的正确方法的想法。
此外,有时解决问题的ViewController后可以从NavParams也许
来自于yesotung,在离子模拟中也有内建:来自“ionic-angular/util/mock-providers”的import {mockApp,mockConfig,mockPlatform,mockView};并使用它像{提供:ViewController,useValue:mockView()}, – eesdil