说说NG里的单元测试

发表于:2015-4-15 10:33

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:feenan    来源:51Testing软件测试网采编

  上面利用了$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开发的同学赶紧把测试补上吧!
33/3<123
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号