摘要: 如何使用Mocha在浏览器中测试JavaScript代码?javascript
本文全部代码都在Fundebug/mocha-browser-test仓库中。css
在玩转Node.js单元测试博客中,我介绍了测试框架Mocha,对后端Node.js代码进行测试。在这篇博客,我将介绍如何使用Mocha在浏览器中测试JavaScript代码。html
安装mocha(在国内使用cnpm比npm更快):前端
sudo cnpm install -g mocha
复制代码
执行mocha init命令,能够自动生成浏览器端的测试文件:java
mocha init test
复制代码
mocha会自动建立一个test目录,其中有4个文件,分别是:node
mocha.js与mocha.css是Mocha模块自身的源代码,由于须要在浏览器中展现测试结果,所以须要Mocha的CSS文件;tests.js为测试代码,为空文件,须要咱们编写;index.html为运行测试的入门页面,使用浏览器大概它就会运行测试,而且展现测试结果。git
index.html是理解Mocha浏览器测试的关键:程序员
<!DOCTYPE html> <html> <head> <title>Mocha</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="mocha.css" /> </head> <body> <div id="mocha"></div> <script src="mocha.js"></script> <script>mocha.setup('bdd');</script> <script src="tests.js"></script> <script> mocha.run(); </script> </body> </html> 复制代码
可知:github
使用mocha init生成的测试代码中没有实际的测试案例,不妨添加一个简单的add.js:npm
function add(a, b) {
return a + b;
}
复制代码
可知,add是一个很是简单的加法函数。
在tests.js添加针对add函数的测试代码:
var should = chai.should();
describe("测试add函数", function() {
it("1加1等于2", function() {
var sum = add(1, 2);
should.equal(sum, 3);
});
it("1加2等于3", function() {
var sum = add(1, 2);
should.equal(sum, 3);
});
});
复制代码
在测试代码中,我使用了断言库Chai。
在index.html中,须要添加源代码add.js以及断言库chai.js:
<!DOCTYPE html>
<html>
<head>
<title>Mocha</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="mocha.js"></script>
<script>mocha.setup('bdd');</script>
<script src="https://cdn.staticfile.org/chai/4.0.0-canary.1/chai.js"></script>
<script src="../add.js"></script>
<script src="tests.js"></script>
<script>
mocha.run();
</script>
</body>
</html>
复制代码
使用浏览器打开index.html,就会运行测试,而且看到运行结果:
可知,测试经过:)
对于习惯在终端敲命令行的程序员来讲,用浏览器打开index.html去进行测试显得很是不合时宜。
还好,有所谓的headless的浏览器PhantomJS,它没有图形界面,却能够运行前端代码,方便用来测试。
安装phantomjs和mocha-phantomjs(phantomjs模块改名为phantomjs-prebuilt):
sudo cnpm install -g phantomjs-prebuilt mocha-phantomjs
复制代码
将Mocha和PhontomJS结合起来的是mocha-phantomjs,在终端执行mocha-phantomjs命令,它会在PhantomJS中执行Mocha测试代码,并将结果展现在终端,很是方便:
mocha-phantomjs --path /usr/local/bin/phantomjs ./test/index.html
测试add函数
✓ 1加1等于2
✓ 1加2等于3
2 passing (7ms)
复制代码
--path选项指定了phantomjs的安装路径。这个必须指定,不然会报错"phantomjs terminated with signal SIGSEGV"。
另外,测试代码tests.js中必须有describe语句,不然使用mocha-phantomjs执行时会报错"mocha.run() was called with no tests"。
mocha-phantomjs的测试命令比较长,能够在package.json中配置npm的test脚本:
"scripts": {
"test": "mocha-phantomjs --path /usr/local/bin/phantomjs ./test/index.html"
},
复制代码
这样,执行npm test命令就能够运行测试。