这篇文章整理一下在Angular 8中使用PhantomJS测试碰到的问题与解决方法。
一般只需要4个步骤,具体如下所示:
步骤1: 安装操作系统对应版本的PhontomJS,并设定 PATH步骤2: 在Angular的应用中安装karma-phantomjs-launcher步骤3: 修改缺省的karma配置文件设定浏览器为PhantomJS,并将karma-phantomjs-launcher添加到plugins中步骤4: 使用ng test执行测试现象就是ng test命令无法正常执行,会提示SyntaxError: Use of reserved word 'class'的错误信息,详细日志如下:
liumiaocn:demo liumiao$ ng test 30% building 16/16 modules 0 active01 11 2019 06:54:19.488:INFO [karma-server]: Karma v4.1.0 server started at http://0.0.0.0:9876/ 01 11 2019 06:54:19.491:INFO [launcher]: Launching browsers PhantomJS with concurrency unlimited 01 11 2019 06:54:19.496:INFO [launcher]: Starting browser PhantomJS 01 11 2019 06:54:22.600:INFO [PhantomJS 2.1.1 (Mac OS X 0.0.0)]: Connected on socket kGGUXbL8vOM7-Gk9AAAA with id 62893849 PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR SyntaxError: Use of reserved word 'class' at http://localhost:9876/_karma_webpack_/polyfills.js:3395:0 PhantomJS 2.1.1 (Mac OS X 0.0.0) ERROR SyntaxError: Use of reserved word 'class' at http://localhost:9876/_karma_webpack_/polyfills.js:3395:0 liumiaocn:demo liumiao$查阅了一些资料,一直没能发现原因和对应方法,直到Angular官方的这个issue才发现了问题所在。
https://github.com/angular/angular-cli/issues/14691虽然这个issues最终也是跟其他类似的issue一样无对应关闭的,但是有人给出了解决的建议方法 在结合错误的提示信息,为什么会说class是保留字,是谁的保留字?是es6的保留字。看了一下tsconfig.spec.json的设定,并没有直接设定target
liumiaocn:demo liumiao$ cat tsconfig.spec.json { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", "types": [ "jasmine", "node" ] }, "files": [ "src/test.ts", "src/polyfills.ts" ], "include": [ "src/**/*.spec.ts", "src/**/*.d.ts" ] } liumiaocn:demo liumiao$而在tsconfig.json中,看到了es6的设定, 如下所示,target被设为了es2015(等同于es6)
liumiaocn:demo liumiao$ cat tsconfig.json { "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "downlevelIteration": true, "experimentalDecorators": true, "module": "esnext", "moduleResolution": "node", "importHelpers": true, "target": "es2015", "typeRoots": [ "node_modules/@types" ], "lib": [ "es2018", "dom" ] }, "angularCompilerOptions": { "fullTemplateTypeCheck": true, "strictInjectionParameters": true } } liumiaocn:demo liumiao$注:关于es6/es2015的来源在以前的文章中有所介绍,就不再赘述。
做如下修改
liumiaocn:demo liumiao$ diff tsconfig.json tsconfig.json.org 13c13 < "target": "es5", --- > "target": "es2015", liumiaocn:demo liumiao$PhantomJS目前已经暂停更新,目前停止在2.1.1版本上 停更的详细的说明 对于一个超过27k点赞的项目停更,确实是一个可惜的事情,然而2019年即将过完,仍然没有中断暂停的迹象。
问题得到解决的方式是将es2015改为es5,这就需要使用者做一个选择,使用es6的新特性还是使用PhantomJS,一般的情况下,使用了PhantomJS的存量系统往往选择后者,而新的系统可能会直接使用Chrome 59之后提供的Headless Mode来取代PhantomJS。
淼叔 认证博客专家 神经网络 TensorFlow NLP 资深架构师,PMP、OCP、CSM、HPE University讲师,EXIN DevOps Professional与DevOps Master认证讲师,曾担任HPE GD China DevOps & Agile Leader,帮助企业级客户提供DevOps咨询培训以及实施指导。熟悉通信和金融领域,有超过十年金融外汇行业的架构设计、开发、维护经验,在十几年的IT从业生涯中拥有了软件开发设计领域接近全生命周期的经验和知识积累,著有企业级DevOps技术与工具实战。