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("<div>{{2+2}}</div>");
//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 <h1 class="ng-binding">...</h1>"
template: '<h1>lidless, wreathed in flame, {{1 + 1}} times</h1>'
};
});
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('<a-great-eye></a-great-eye>')($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 $injector 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': https://github.com/karma-runner/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('<a-great-eye></a-great-eye>')($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*/
<h1>lidless, wreathed in flame, {{1 + 1}} times</h1>

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('<a-great-eye></a-great-eye>')($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('<div a-great-eye flavor="goPro"></div>')($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('<div a-great-eye flavor="goPro"></div>')($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('<error></error>')($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";
});

[Unit Testing] AngularJS Unit Testing - Karma的更多相关文章

  1. Unit Testing, Integration Testing and Functional Testing

    转载自:https://codeutopia.net/blog/2015/04/11/what-are-unit-testing-integration-testing-and-functional- ...

  2. Difference Between Performance Testing, Load Testing and Stress Testing

    http://www.softwaretestinghelp.com/what-is-performance-testing-load-testing-stress-testing/ Differen ...

  3. AngularJS测试框架 karma备忘

    AngularJS测试框架karma安装 安装karma $ --save-dev 安装karma组件 $ npm install karma-jasmine karma-chrome-launche ...

  4. Go testing 库 testing.T 和 testing.B 简介

    testing.T 判定失败接口 Fail 失败继续 FailNow 失败终止 打印信息接口 Log 数据流 (cout 类似) Logf format (printf 类似) SkipNow 跳过当 ...

  5. [Angular + Unit] AngularJS Unit testing using Karma

    http://social.technet.microsoft.com/wiki/contents/articles/32300.angularjs-unit-testing-using-karma- ...

  6. [AngularJS Unit tesint] Testing keyboard event

    HTML: <div ng-focus="vm.onFocus(month)", aria-focus="{{vm.focus == month}}", ...

  7. [AngularJS + Unit Testing] Testing Directive's controller with bindToController, controllerAs and isolate scope

    <div> <h2>{{vm.userInfo.number}} - {{vm.userInfo.name}}</h2> </div> 'use str ...

  8. [AngularJS + Unit Testing] Testing a component with requiring ngModel

    The component test: describe('The component test', () => { let component, $componentController, $ ...

  9. [Unit Testing] Fundamentals of Testing in Javascript

    In this lesson, we’ll get the most fundamental understanding of what an automated test is in JavaScr ...

随机推荐

  1. 安装Tomcat服务器

    一.首先,下载Tomcat,你可以直接百度Tomcat官网, 或者,直接在地址栏输入他的官网地址:http://tomcat.apache.org/,然后进入他的主页,在主页左侧可以找到Downloa ...

  2. Incompatible operand types DeptE and int 异常处理

    Incompatible operand types DeptE and int 1.java不会运算到==的值,把==改为equals 2.java不会运算到eequals的值 把equals的改为 ...

  3. Window程序的安装与部署

    步骤: 1.新建项目—选择安装与部署—安装项目或使用安装向导,再这里我用的是安装向导 2.点击确定—下一步 3.点击下一步,选择主输出 4.点击下一步,添加文件 5.点击完成 设置: 右击安装项目 出 ...

  4. C语言中的内存分配与释放

    C语言中的内存分配与释放 对C语言一直都是抱着学习的态度,很多都不懂,今天突然被问道C语言的内存分配问题,说了一些自己知道的,但感觉回答的并不完善,所以才有这篇笔记,总结一下C语言中内存分配的主要内容 ...

  5. spring mvc 配置对静态资源的访问

    在spring mvc的配置文件中做如下配置: 1. <?xml version="1.0" encoding="UTF-8"?> <bean ...

  6. JavaScript 函数惰性载入

    最近看JavaScript高级程序设计,大有收获,接下来几天写一下读书笔记.之前写了一篇Ajax初步理解的随笔,里面有个函数用来创建XmlHttpRequest对象,浏览器兼容性原因,写出的代码通过大 ...

  7. 基于iscroll.js实现下拉刷新和上拉加载特效

    现在已经不是纯Android独霸天下的时代了,H5嵌入Android的Hybrid混合开发是大势所趋.今天给大家带来的就是移动端中常见的"上拉刷新,下拉加载"特效,这个特效将会基于 ...

  8. Qt学习笔记:Qt中使用Lua

    今天想在Qt中使用Lua进行数据操作 结果发现在Qt中使用Lua的文章较少,虽然很简单,但是还是写出来提供入门,顺便记录一下 我使用的是Qt Creator 3.4.2,用的是mingw4.9.2的编 ...

  9. jquery时间倒计时

    代码: js: function countDown(time, id) {  //time的格式yyyy/MM/dd hh:mm:ss    var day_elem = $(id).find('. ...

  10. Android shape 渐变!描边!圆角!示例详解

    看看shape的用法,确实很有帮助.这里我偷懒转一篇比较详细的帖子,和大家一起进步~! Android 中常常使用shape来定义控件的一些显示属性,今天看了一些shape的使用,对shape有了大体 ...