说说NG里的单元测试
作者:网络转载 发布时间:[ 2015/4/15 11:14:30 ] 推荐标签:单元测试 软件测试技术 模块
上面利用了$rootScope来创建子作用域,然后把这个参数传进控制器的构建方法$controller里去,终会执行上面的控制器里的方法,然后我们检查子作用域里的数组数量以及字符串变量是否跟期望的值相等.
想要了解更多关于ng里的控制器的信息,可以点击这里
ng里指令的单元测试
定义一个简单的指令
var app = angular.module('myApp', []);
app.directive('aGreatEye', function () {
return {
restrict: 'E',
replace: true,
template: '<h1>lidless, wreathed in flame, {{1 + 1}} times</h1>'
};
});
然后我们编写一个简单的测试脚本
describe('Unit testing great quotes', function() {
var $compile;
var $rootScope;
// Load the myApp module, which contains the directive
beforeEach(module('myApp'));
// Store references to $rootScope and $compile
// so they are available to all tests in this describe block
beforeEach(inject(function(_$compile_, _$rootScope_){
// The injector unwraps the underscores (_) from around the parameter names when matching
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('Replaces the element with the appropriate content', function() {
// Compile a piece of HTML containing the directive
var element = $compile("<a-great-eye></a-great-eye>")($rootScope);
// fire all the watches, so the scope expression {{1 + 1}} will be evaluated
$rootScope.$digest();
// Check that the compiled element contains the templated content
expect(element.html()).toContain("lidless, wreathed in flame, 2 times");
});
});
上面的例子来自于官方提供的,终上面的指令将会这用在html里使用
<a-great-eye></a-great-eye>
测试脚本里首先注入$compile与$rootScope两个服务,一个用来编译html,一个用来创建作用域用,注意这里的_,默认ng里注入的服务前后加上_时,后会被ng处理掉的,这两个服务保存在内部的两个变量里,方便下面的测试用例能调用到
$compile方法传入原指令html,然后在返回的函数里传入$rootScope,这样完成了作用域与视图的绑定,后调用$rootScope.$digest来触发所有监听,保证视图里的模型内容得到更新
然后获取当前指令对应元素的html内容与期望值进行对比.
想要了解更多关于ng里的指令的信息,可以点击这里
ng里的过滤器单元测试
定义一个简单的过滤器
var app = angular.module('myApp', []);
app.filter('interpolate', ['version', function(version) {
return function(text) {
return String(text).replace(/\%VERSION\%/mg, version);
};
}]);
然后编写一个简单的测试脚本
describe('filter', function() {
beforeEach(module('myApp'));
describe('interpolate', function() {
beforeEach(module(function($provide) {
$provide.value('version', 'TEST_VER');
}));
it('should replace VERSION', inject(function(interpolateFilter) {
expect(interpolateFilter('before %VERSION% after')).toEqual('before TEST_VER after');
}));
});
});
上面的代码先配置过滤器模块,然后定义一个version值,因为interpolate依赖这个服务,后用inject注入interpolate过滤器,注意这里的过滤器后面得加上Filter后缀,后传入文本内容到过滤器函数里执行,与期望值进行对比.
总结
利用测试来开发NG有很多好处,可以保证模块的稳定性,还有一点是能够深入的了解ng的内部运行机制,所以建议用ng开发的同学赶紧把测试补上吧!
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系SPASVO小编(021-61079698-8054),我们将立即处理,马上删除。
相关推荐
iOS单元测试mocha、chai、sinon和istanbul实现百分之百的单元测试覆盖率关于单元测试的总结及思考编写更好的Java单元测试的7个技巧Android单元测试框架Robolectric3.0介绍(一)使用Kiwi单元测试总结单元测试如此重要,为什么你不知道Python单元测试??使用装饰器实现测试跳过和预期故障对Controller的单元测试写好单元测试的10个技巧单元测试的重要性Angular单元测试系列??Component、Directive、Pipe 以及ServiceAndroid单元测试的整理提升单元测试体验的利器--Mockito使用总结iOS UnitTest单元测试Vue的单元测试探索(二)

sales@spasvo.com