博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Unit Testing] AngularJS Unit Testing - Karma
阅读量:5040 次
发布时间:2019-06-12

本文共 9801 字,大约阅读时间需要 32 分钟。

Install Karam:

npm install -g karma
npm install -g karma-cli

 

Init Karam:

karma init

 

First test:

1. Add test file to the karma.conf.js:

// list of files / patterns to load in the browser    files: [        'test/hello.js'    ],

2. Add test file:

describe('First Unit testing with Karma', function() {    it('sholud work', function() {        expect(true).toBe(false);    })})

Of course, it will failed. 

Then we make it pass:

describe('First Unit testing with Karma', function() {    it('sholud work', function() {        expect(true).toBe(true);    })})

 

Testing with AngularJS


 

Install angular-mocks:

npm install angular-mocks

 

Include the angular.js and angular-mocks.js file before the test file:

// list of files / patterns to load in the browser    files: [        'test/hello.js',        'bower_components/angular/angular.js',        'node_modules/angular-mocks/angular-mocks.js',        'test/anuglarjs.js'    ],

 

Write the test file:

describe('Testing with AngularJS', function() {    //Want $scope and element can be used globally    var $scope,        element;    //We need to inject $compile, $rootScope    beforeEach(inject(function($compile, $rootScope) {        $scope = $rootScope;        //create an 'angular element'        element = angular.element("
{
{2+2}}
"); //then compile it to real angular element //also it requires link function and scope element = $compile(element)($rootScope); })); it('should equals to 4', function() { //make sure to $digest() it to get the change $scope.$digest(); expect(element.html()).toBe("5"); // change to "4" to make it pass })})

Now, "4" is not "5", then it will failed, switch to "4" to make it pass.

 

Testing Directive:


 

.directive('aGreatEye', function () {        return {            restrict: 'E',            replace: true,   //Important to add replace: true, otherwise, it would be 

...

" template: '

lidless, wreathed in flame, {
{1 + 1}} times

' }; });

 

describe('Testing directive', function() {    var $scope,        $compile,        element;    beforeEach(module('app'));    beforeEach(inject(function(_$compile_, _$rootScope_) {        $compile = _$compile_;        $scope = _$rootScope_;    }));    it("Replaces the element with the appropriate content", function() {        element = $compile('
')($scope); $scope.$digest(); expect(element.html()).toBe('lidless, wreathed in flame, 2 times'); })});

Underscore notation: The use of the underscore notation (e.g.: _$rootScope_) is a convention wide spread in AngularJS community to keep the variable names clean in your tests. That's why the  strips out the leading and the trailing underscores when matching the parameters. The underscore rule applies only if the name starts and ends with exactly one underscore, otherwise no replacing happens.

 

Testing Directives With External Templates:


 

1. Install 'karma-ng-html2js-preprocessor': 

npm install karma-ng-html2js-preprocessor --save-dev

 

2. Add config to karma.config.js:

// preprocess matching files before serving them to the browser    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor    preprocessors: {        '*.html': ['ng-html2js']    },      ngHtml2JsPreprocessor: {          // strip this from the file path          stripPrefix: '/'  //because currently all the html files are located in / root      },

 

3. Add html into beforeEach:

describe('Testing directive', function() {    var $scope,        $compile,        element;    beforeEach(module('app'));    // Add html file here    beforeEach(module('directivetest.html'));    beforeEach(inject(function(_$compile_, _$rootScope_) {        $compile = _$compile_;        $scope = _$rootScope_;    }));    it("Replaces the element with the appropriate content", function() {        element = $compile('
')($scope); $scope.$digest(); expect(element.html()).toBe('lidless, wreathed in flame, 2 times'); })});

 

.directive('aGreatEye', function () {        return {            restrict: 'E',            replace: true,            templateUrl: 'directivetest.html'        };    });   /*directivetest.html*/   

lidless, wreathed in flame, {
{1 + 1}} times

 

Testing Directive Scope:


 

1. Check after a click event, scope value changed:

.directive('aGreatEye', function () {        return {            restrict: 'EA',            replace: true,            templateUrl: 'directivetest.html',            link: function(scope, element) {                scope.isClicked = false;                element.bind('click', function() {                    scope.isClicked = true;                })            }        };    });

 

it("isClicked is true after click", function() {        element = $compile('
')($scope); $scope.$digest(); element.triggerHandler('click'); expect($scope.isClicked).toBe(true); });

 

2. Isolated scope testing:

.directive('aGreatEye', function () {        return {            restrict: 'EA',            replace: true,            scope: {},            templateUrl: 'directivetest.html',            link: function(scope, element) {                scope.isClicked = false;                element.bind('click', function() {                    scope.isClicked = true;                })            }        };    });

 

it("isolated scope testing", function() {        element.triggerHandler('click');        expect(element.isolateScope().isClicked).toBe(true);    });

 

You can no long use "element.scope()" or "$scope", you should use "element.isolateScope()".

 

Testing Directive Scope Binding:


 

Tow ways binding:

.directive('aGreatEye', function () {        return {            restrict: 'EA',            replace: true,            scope: {                flavor: "=" //Accpet an object            },            templateUrl: 'directivetest.html',            link: function(scope, element) {                element.bind('click', function() {                    scope.isClicked = true;                    scope.flavor.message += " World!";                })            }        };    });

 

beforeEach(inject(function(_$compile_, _$rootScope_) {        $compile = _$compile_;        $scope = _$rootScope_;        $scope.goPro = {message: "Hello"};        element = $compile('
')($scope); $scope.$digest(); })); it("after click the scope.data should be Hello World!", function() { element.triggerHandler('click'); expect($scope.goPro.message).toBe('Hello World!'); expect(element.isolateScope().flavor.message).toBe("Hello World!"); });

 

Testing Speed:


 Using ddescriber plugin to speed up unit testing.

Install the plugin "ddscriber for jasmine". Ctrl+Shift+D, to open the dailog. In the dialog you can choose which test to be included or not.

The code is modfied as: 

/** * Created by Answer1215 on 1/16/2015. */ddescribe('Testing directive', function() {    var $scope,        $compile,        element;    beforeEach(module('app'));    beforeEach(module('directivetest.html'));    beforeEach(inject(function(_$compile_, _$rootScope_) {        $compile = _$compile_;        $scope = _$rootScope_;        $scope.goPro = {message: "Hello"};        element = $compile('
')($scope); $scope.$digest(); })); iit("Replaces the element with the appropriate content", function() { expect(element.html()).toContain("lidless, wreathed in flame, 2 times"); }); //it("isClicked is true after click", function() {
// element.triggerHandler('click'); // expect($scope.isClicked).toBe(true); //}); iit("isolated scope testing", function() { element.triggerHandler('click'); //expect(element.isolateScope().isClicked).toBe(true); }); xit("after click the scope.data should be Hello World!", function() { element.triggerHandler('click'); expect($scope.goPro.message).toBe('Hello World!'); //expect(element.isolateScope().flavor.message).toBe("Hello World!"); });});xdescribe("error driective testing", function() { var $scope, $compile, element; beforeEach(module('app')); beforeEach(module('error.html')); beforeEach(inject(function(_$compile_, _$rootScope_) { $scope = _$rootScope_; $compile = _$compile_; element = $compile('
')($scope); $scope.$digest(); })); iit("Should contains alert-danger class", function() { expect(element.find('div').hasClass('alert-danger')).toBe(true); });});

 

ddscribe / iit  -- include

xdscribe / xit -- exclude

 

Testing Service:


 Testing service, you need to inject the service into beforeEach.

ddescribe('testing service', function() {    var SmithService;    beforeEach(module('app'));    beforeEach(inject(function(_SmithService_) {        SmithService = _SmithService_;    }));    iit('should append Smith after each name', function() {        expect(SmithService.getName("John")).toBe("John Smith");    })});

This testing case is test whenever use a service to get a name we will append " Smith" to the end.

 

.service('SmithService', function() {        var SmithService = {};        SmithService.getName = function(name) {            return name + " Smith";        }        return SmithService;    });

 

Testing Controller:


 Testing controller, you need to inject the $controller into beforeEach. And get ctrl instence by using:

appCtrl = $controller("AppCtrl")

 

ddescribe('Test Controller', function() {    var ctrl;    beforeEach(module('app'));    beforeEach(inject(function(_$controller_) {        ctrl = _$controller_("TestCtrl");    }));    iit('Test Controller', function() {        expect(ctrl.message).toBe("Hello");    });});

 

.controller('TestCtrl', function() {        var vm = this;        vm.message = "Hello";    });

 

转载于:https://www.cnblogs.com/Answer1215/p/4230083.html

你可能感兴趣的文章
软件开发中对架构、构架、结构、框架的理解
查看>>
JAVA通信系列一:Java Socket技术总结
查看>>
VS 2010打开设计器出现错误
查看>>
SQLServer 镜像功能完全实现
查看>>
Vue-详解设置路由导航的两种方法
查看>>
一个mysql主从复制的配置案例
查看>>
大数据学习系列(8)-- WordCount+Block+Split+Shuffle+Map+Reduce技术详解
查看>>
dvwa网络渗透测试环境的搭建
查看>>
Win8 安装VS2012 和 Sql Server失败问题
查看>>
过点(2,4)作一直线在第一象限与两轴围成三角形,问三角形面积的最小值?...
查看>>
java aes CBC的填充方式发现
查看>>
使用ionic cordova build android --release --prod命令打包报有如下错误及解决方法
查看>>
BZOJ 2338 HNOI2011 数矩形 计算几何
查看>>
关于页面<!DOCTYPE>声明
查看>>
【AS3代码】播放FLV视频流的三步骤!
查看>>
C++标准库vector使用(更新中...)
查看>>
cocos2d-x 2.2.6 之 .xml文件数据读取
查看>>
枚举的使用
查看>>
BZOJ 1531 二进制优化多重背包
查看>>
BZOJ 2324 (有上下界的)费用流
查看>>