一. Angular單元測(cè)試
https://angular.io/guide/testing
進(jìn)行Ionic單元測(cè)試之前辕狰,可以大概了解下Angular單元測(cè)試永乌。這樣可以幫助我們更好的進(jìn)行Ionic單元測(cè)試镣奋。
二. Ionic test example
- 下載地址
https://github.com/ionic-team/ionic-unit-testing-example
2.測(cè)試的名字和位置
如上圖: 文件的名字約定為 *.spec.ts, 文件的位置放在 page1.ts相同的路徑
3.app.component.ts文件
import { async, TestBed } from '@angular/core/testing';
import { IonicModule, Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { MyApp } from './app.component';
import {
PlatformMock,
StatusBarMock,
SplashScreenMock
} from '../../test-config/mocks-ionic';
describe('MyApp Component', () => {
let fixture;
let component;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyApp],
imports: [
IonicModule.forRoot(MyApp)
],
providers: [
{ provide: StatusBar, useClass: StatusBarMock },
{ provide: SplashScreen, useClass: SplashScreenMock },
{ provide: Platform, useClass: PlatformMock }
]
})
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyApp);
component = fixture.componentInstance;
});
it('should be created', () => {
expect(component instanceof MyApp).toBe(true);
});
it('should have two pages', () => {
expect(component.pages.length).toBe(2);
});
});
expect(component.pages.length).toBe(2);
該測(cè)試用例代表pages個(gè)數(shù)為2時(shí)武氓,測(cè)試pass
- page1.spec.ts文件
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { Page1 } from './page1';
import { IonicModule, Platform, NavController} from 'ionic-angular/index';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { PlatformMock, StatusBarMock, SplashScreenMock } from '../../../test-config/mocks-ionic';
describe('Page1', () => {
let de: DebugElement;
let comp: Page1;
let fixture: ComponentFixture<Page1>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [Page1],
imports: [
IonicModule.forRoot(Page1)
],
providers: [
NavController,
{ provide: Platform, useClass: PlatformMock},
{ provide: StatusBar, useClass: StatusBarMock },
{ provide: SplashScreen, useClass: SplashScreenMock },
]
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(Page1);
comp = fixture.componentInstance;
de = fixture.debugElement.query(By.css('h3'));
});
it('should create component', () => expect(comp).toBeDefined());
it('should have expected <h3> text', () => {
fixture.detectChanges();
const h3 = de.nativeElement;
expect(h3.innerText).toMatch(/ionic/i,
'<h3> should say something about "Ionic"');
});
});
- 運(yùn)行單元測(cè)試
下載Sample后坛增,運(yùn)行
npm install
安裝建椰。
然后使用下面命令雕欺,進(jìn)行單元測(cè)試
npm run test
- 計(jì)算單元測(cè)試覆蓋率
npm run test-coverage
運(yùn)行后,將在工程根路徑下創(chuàng)建coverage文件棉姐,在coverage里屠列,打開index.html,就能夠查看覆蓋率