用karma测试angularjs应用

本文介绍了如何使用Karma自动化测试框架进行项目测试配置及运行流程,并通过实例演示了如何编写测试用例来验证功能实现。

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

介绍网上有很多就不赘述了

Karma的安装

sudo npm install karma -g

网上只给了这步,由于版本迭代会导致本地找不到KARMA命令。像很多模块的最新版本一样,只需再安装个客户端就OK了

sudo npm install karma-cli -g


再进到项目目录初始化

karma init
Which testing framework do you want to use ?
Press tab to list possible options. Enter to move to the next question.
> jasmine


Do you want to use Require.js ?
This will add Require.js plugin.
Press tab to list possible options. Enter to move to the next question.
> no


Do you want to capture any browsers automatically ?
Press tab to list possible options. Enter empty string to move to the next question.
> Chrome
>


What is the location of your source and test files ?
You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
Enter empty string to move to the next question.
>


Should any of the files included by the previous patterns be excluded ?
You can use glob patterns, eg. "**/*.swp".
Enter empty string to move to the next question.
>


Do you want Karma to watch all the files and run the tests on change ?
Press tab to list possible options.
> yes




Config file generated at "/你的项目路径/karma.conf.js".

运行Karma


</pre><p><pre name="code" class="html">karma start karma.conf.js

以逆转字符串为例

home.js

function reverse(name){
    return name.split("").reverse().join("");
}

home.test.js

describe("A suite of basic functions", function() {
    it("reverse word",function(){
        expect("DCBA").toEqual(reverse("ABCD"));
        expect("Conan").toEqual(reverse("nano"));
    });
});

启动后会在终端中看到

karma start karma.config.js
INFO [karma]: Karma v0.12.31 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 41.0.2272 (Mac OS X 10.10.2)]: Connected on socket VqxM2bXSv64g2MlvUIK_ with id 29138942
Chrome 41.0.2272 (Mac OS X 10.10.2) A suite of basic functions reverse word FAILED
	Expected 'Conan' to equal 'onan'.
	    at Object.<anonymous> (/Users/Nathan/Workspaces/hnczb-web/test/home.test.js:4:25)
Chrome 41.0.2272 (Mac OS X 10.10.2): Executed 1 of 1 (1 FAILED) (0 secs / 0.009 Chrome 41.0.2272 (Mac OS X 10.10.2): Executed 1 of 1 (1 FAILED) ERROR (0.014 secs / 0.009 secs)

注释掉
//expect("Conan").toEqual(reverse("nano"));
INFO [watcher]: Changed file "/Users/Nathan/Workspaces/hnczb-web/test/home.test.js".
Chrome 41.0.2272 (Mac OS X 10.10.2): Executed 1 of 1 SUCCESS (0 secs / 0.003 secChrome 41.0.2272 (Mac OS X 10.10.2): Executed 1 of 1 SUCCESS (0.007 secs / 0.003 secs)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值