这篇文章记录了使用github上的一个含有单元测试配置的Ionic项目改造自己的项目,使自己的项目也能跑单元测试。
Ionic版本3.x,参考的github项目地址:https://github.com/ionic-team/ionic-unit-testing-example
修改自己的项目步骤如下:
1、将示例项目的devDependencies中的依赖增加到自己的项目中,主要需要如下依赖
"@angular/cli": "1.4.8",
"@ionic/app-scripts": "3.1.8",
"@types/jasmine": "^2.5.41",
"@types/node": "^8.0.45",
"angular2-template-loader": "^0.6.2",
"html-loader": "^0.5.1",
"istanbul-instrumenter-loader": "^3.0.0",
"jasmine": "^2.5.3",
"jasmine-spec-reporter": "^4.1.0",
"karma": "^1.5.0",
"karma-chrome-launcher": "^2.0.0",
"karma-coverage-istanbul-reporter": "^1.3.0",
"karma-jasmine": "^1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"karma-sourcemap-loader": "^0.3.7",
"karma-webpack": "^2.0.3",
"null-loader": "^0.1.1",
"protractor": "^5.1.1",
"ts-loader": "^3.0.3",
"ts-node": "^3.0.2",
"typescript": "2.4.2"
检查是否和项目中的一些依赖重复,如果重复检查版本号。
2、重新执行npm install,下载依赖包;
3、将示例项目中package.json中的scripts复制到自己的项目中。
"scripts": {
"clean": "ionic-app-scripts clean",
"build": "ionic-app-scripts build",
"ionic:build": "ionic-app-scripts build",
"ionic:serve": "ionic-app-scripts serve",
"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"
},
4、将示例项目中的test-config目录拷贝到自己的项目中,tsconfig.json也可以复制覆盖。
5、新建一个测试文件xxx.spec.ts,编写测试用例用于测试环境是否搭建成功。
6、执行命令npm run test,检查是否成功。同时我们可以发现npm run test-coverage可以检查测试覆盖率,npm run test-ci也可以在流水线上执行。
使用官网的ionic测试项目步骤到此结束,接下来说说遇到的问题。
1、执行npm run test时报错,cannot find name describe(it expect),并且在vscode编辑器中提示测试文件中的describe无法找到对应方法。
一顿乱搜,最后发现是因为@types/jasmine的版本和typescript版本不匹配,猜测是因为版本号^2.5.41会下载到2.x中最新的版本,所以尝试下载2.5.41这一个固定版本,问题解决。
当上述的方法无法解决问题的时候及,尝试第二种方法,在tsconfig.json中的exclude中排除spec.ts相关的内容:
"exclude": [
"node_modules",
"**/*.spec.ts"
]
2、执行npm run build --prod --aot命令时报错: cannot read property flags of undefined。
stackoverflow记录的错误原因是:
Removing @angular/cli should work for you
if not, change Typescript version to ~2.6.2.
@angular/cli 1.7.3 works with Typescript ~2.6.2 only.
来自 <https://stackoverflow.com/questions/49544854/typeerror-cannot-read-property-flags-of-undefined>
检查了自己的package.json发现@angular/cli也是1.7.x的版本,更换了typescript版本,再运行,测试和生产打包均通过。