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