下面的介绍以karma能正常运行为前提,看karma系列文章:http://www.cnblogs.com/laixiangran/tag/Karma/
目录结构
步骤
安装
npm install angular --save-dev
npm install angular-mocks --save-dev //专门用来进行单元测试的模块
karma.conf.js
/***
* Created by laixiangran on 2015/12/22.
* karma单元测试配置文件
*/ module.exports = function(config) { config.set({ /***
* 基础路径,用在files,exclude属性上
*/
basePath: "", /**
* 测试框架
* 可用的框架:https://npmjs.org/browse/keyword/karma-adapter
*/
frameworks: ["jasmine"], /**
* 需要加载到浏览器的文件列表
*/
files: [
"../node_modules/angular/angular.js",
"../node_modules/angular-mocks/angular-mocks.js",
"karmaTest/test.js",
"karmaTest/test.spec.js"
]
});
};
test.js
/**
* Created by laixiangran on 2015/12/20.
*/ var app = angular.module("myApp", []); app.controller("myCtrl", ["$scope", function ($scope) { var vm = $scope.vm = {
htmlSource: "",
showErrorType: 1,
showDynamicElement: true
}; $scope.testTxt = "hello unit test!"; $scope.setTxt = function (txt) {
$scope.testTxt = txt;
}; $scope.getTxt = function () {
return $scope.testTxt;
}; $scope.removeTxt = function () {
delete($scope.testTxt);
}; $scope.chooseTxt = function (val) {
return val == "t" ? "hello unit test!" : "hello world!";
}; }]);
test.spec.js
/**
* Created by laixiangran on 2015/12/20.
*/
describe("myCtrl测试", function() {
var scope = null;
var testCtrl = null; // module是angular.mock.module方法,用来配置inject方法注入的模块信息,参数可以是字符串、函数、对象
beforeEach(module("myApp"));
// inject是angular.mock.inject方法,用来注入module配置好的ng模块,方便在it的测试函数里调用
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
//初始化myCtrl
testCtrl = $controller("myCtrl", {$scope:scope});
})); it("validateCtrl必须定义", inject(function($controller) {
expect(testCtrl).toBeDefined();
})); it("scope.testTxt = 'hello unit test!'",function() {
expect(scope.testTxt).toBe("hello unit test!");
}); it("scope.setTxt('hello world!'),scope.testTxt = 'hello world!'",function() {
scope.setTxt("hello world!");
expect(scope.testTxt).toBe("hello world!");
}); it("scope.chooseTxt('t')必须返回'hello unit test!'",function() {
expect(scope.chooseTxt("t")).toBe("hello unit test!");
}); });