下麵的介紹以karma能正常運行為前提,看karma系列文章:http://www.cnblogs.com/laixiangran/tag/Karma/目錄結構步驟安裝npm install angular --save-devnpm install angular-mocks --save-dev...
下麵的介紹以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!"); }); });