在文件html中新建html文件index.html,加入两个输入框用户获取输入,当输入后绑定controller中的add方法实现计算器功能,代码如下:
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<div ng-controller="indexCtrl">
<input type="text" ng-model="a" value="0">
+
<input type="text" ng-model="b" value="0">
=<span id='result'>{{add(a,b)}}</span>
</div>
</body>
</html>
<script src="/bower_components/angular/angular.min.js"></script>
<script src="/bower_components/angular-mocks/angular-mocks.js"></script>
<script src="/js/index.js"></script>
  启动服务器看到下图效果

  编写测试代码
  在test文件夹中新建文件index-test.js用于编写index.js的单元测试。
'use strict';
describe('app', function () {
beforeEach(module('app'));
describe('indexCtrl', function () {
it('add 测试', inject(function ($controller) {
var $scope = {};
//spec body
var indexCtrl = $controller('indexCtrl', {$scope: $scope});
expect(indexCtrl).toBeDefined();
expect($scope.add(2, 3)).toEqual(5);
}));
});
});
  单元测试配置
  初始化karma配置文件,用于配置karma,执行命令
  karma init
  在karma配置文件代码中每个节点都有默认注释请参看
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: './',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.min.js',
'bower_components/angular-mocks/angular-mocks.js',
'js/index.js',
'test/index-test.js'
],
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
plugins: [
'karma-chrome-launcher',
'karma-jasmine',
'karma-junit-reporter'
],
junitReporter: {
outputFile: '/test_out/unit.xml',
suite: 'unit'
}
})
}
  在package.json scripts 配置测试信息,指定karma文件地址
  "test": "karma start karma.conf.js",
  运行单元测试
  运行命令,执行测试
  npm test
  运行结果如下,可以看到通过测试:

  调试单元测试
  除了运行测试外,很多时候需要调试测试,在karma弹出网页中点击debug,进入http://localhost:9876/debug.html页面,可以用chrome自带的调试工具调试代码了: