一. Angular单元测试
https://angular.io/guide/testing
进行Ionic单元测试之前,可以大概了解下Angular单元测试。这样可以帮助我们更好的进行Ionic单元测试。
二. Ionic test example
- 下载地址
https://github.com/ionic-team/ionic-unit-testing-example
2.测试的名字和位置
image.png
如上图: 文件的名字约定为 *.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);
该测试用例代表pages个数为2时,测试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"');
});
});
- 运行单元测试
下载Sample后,运行
npm install
安装。
然后使用下面命令,进行单元测试
npm run test
- 计算单元测试覆盖率
npm run test-coverage
运行后,将在工程根路径下创建coverage文件,在coverage里,打开index.html,就能够查看覆盖率
image.png
网友评论