首先承认,为app添加单元测试的重要性。
如果你觉得不那么重要,可参考《代码的免疫系统- 单元测试》。
选Karma作为你的运行环境的测试,Jasmine作为你实际的测试case。(当然你有其他的选择)
前端的测试分类:分为单元测试和end-to-end测试
单元测试是独立于组件的测试。
e2e是用浏览器的自动点击等行为模拟人的使用行为来测试整个app的。e2e采用的是selenium测试。
下面我们重点介绍为Ionic工程搭建单元测试的框架。
1. 首先下载一个测试的例子
ionic-unit-testing-example,因为需要从测试的例子中copy一些测试的必要的文件。
当然也可以从下面的网站中下载source code。
https://github.com/ionic-team/ionic-unit-testing-example
2. 新建一个ionic工程
$ ionic start starter-with-testing sidemenu
需要保证此工程是可运行的。
$cd starter-with-testing
$ ionic serve
3. 安装测试所需要的node modules
npm install --save-dev angular2-template-loader html-loader jasmine jasmine-spec-reporter karma karma-chrome-launcher karma-jasmine karma-jasmine-html-reporter karma-sourcemap-loader karma-webpack karma-coverage-istanbul-reporter istanbul-instrumenter-loader null-loader protractor ts-loader ts-node @types/jasmine @types/node
4. 准备测试编译的环境
给package.json中添加一些脚本,用于test的编译。
在“scripts”节点中增加
"test": "karma start ./test-config/karma.conf.js",
"test-ci": "karma start ./test-config/karma.conf.js --single-run",
"test-coverage": "karma start ./test-config/karma.conf.js --coverage",
"e2e": "npm run e2e-update && npm run e2e-test",
"e2e-test": "protractor ./test-config/protractor.conf.js",
"e2e-update": "webdriver-manager update --standalone false --gecko false"
5. 增加配置文件
从第一步中的ionic-unit-testing-example拷贝test-config目录到工程的根目录下。
6. 为你的工程增加单元测试
上面的步骤都成功之后,说明你的工程的测试框架已经搭建好,这时你可以写自己的单元测试了。
如给app.component.ts增加单元测试app.component.spec.ts,源码在下面。
7. 运行单元测试
$ npm test
可以通过karma的debug,进入source的webpack进行source code的调试。
改变源码或test,保存,测试程序会自动编译并运行。
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);
});
});
参考文献:https://leifwells.github.io/2017/08/27/testing-in-ionic-configure-existing-projects-for-testing/