JS测试框架Karma安装使用

本文介绍如何安装NodeJS及Karma,并配置Karma进行JavaScript单元测试。具体步骤包括安装NodeJS、设置测试环境、安装及配置Karma及其插件、启动Karma服务器等。此外还提供了一个简单的单元测试示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.安装NodeJS

可以在http://nodejs.org/download/ 下载,我下载的是windows版本。

 

2.安装karma

  新建一个目录如:E:\JavaScript\karma

  E:\JavaScript\karma>npm install karma --save-dev

  E:\JavaScript\karma>npm install karma-jasmine karma-chrome-launcher --save-dev   //安装chrome插件

 其它相关插件需要的话也可以安装,如:

 npm karma-firefox-launcher #firefox浏览器插件  
 npm karma-junit-reporter #junit 测试报告插件  
 npm karma-coverage #单元测试覆盖率插件  

  验证是否安装成功:

  E:\JavaScript\karma>karma start
  INFO [karma]: Karma v0.12.17 server started at http://localhost:9876/
  INFO [Chrome 36.0.1985 (Windows 7)]: Connected on socket McpCZbkxpU1Qg-mtrrdj wi
  th id manual-1692

  可以在本机访问URL: http://localhost:9876,页面显示如下:

  

3.配置Karma

  可以用karma int命令创建karma.config.js配置文件

[plain]  view plain copy
 
  1. E:\JavaScript\karma>karma init  
  2.   
  3. Which testing framework do you want to use ?  
  4. Press tab to list possible options. Enter to move to the next question.  
  5. > jasmine  
  6.   
  7. Do you want to use Require.js ?  
  8. This will add Require.js plugin.  
  9. Press tab to list possible options. Enter to move to the next question.  
  10. > no  
  11.   
  12. Do you want to capture any browsers automatically ?  
  13. Press tab to list possible options. Enter empty string to move to the next quest  
  14. ion.  
  15. > Chrome  
  16. >  
  17.   
  18. What is the location of your source and test files ?  
  19. You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".  
  20. Enter empty string to move to the next question.  
  21. >  
  22.   
  23. Should any of the files included by the previous patterns be excluded ?  
  24. You can use glob patterns, eg. "**/*.swp".  
  25. Enter empty string to move to the next question.  
  26. >  
  27.   
  28. Do you want Karma to watch all the files and run the tests on change ?  
  29. Press tab to list possible options.  
  30. > yes  
  31.   
  32.   
  33. Config file generated at "E:\JavaScript\karma\karma.conf.js".  


4.安装karma-jasmine

 

E:\JavaScript\karma>npm install karma-jasmine

5.JS单元测试举例

 

 

参考文档:

1.http://karma-runner.github.io/0.12/index.html

2.http://blog.youkuaiyun.com/puncha/article/details/18384289

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值