单元测试 – 如何在AngularJS中的指令单元测试中注入服务
发布时间:2020-12-17 08:28:53 所属栏目:安全 来源:网络整理
导读:我需要测试一个指令,对一些注入的服务做一些调用。 下面的代码是一个示例指令,监听事件,如果在指定的元素内按下enter键,则重定向浏览器。 编辑:我得到我可能在涉及E2E测试土地的感觉? angular.module('fooApp') .directive('gotoOnEnter',['$location'
我需要测试一个指令,对一些注入的服务做一些调用。
下面的代码是一个示例指令,监听事件,如果在指定的元素内按下enter键,则重定向浏览器。 编辑:我得到我可能在涉及E2E测试土地的感觉? angular.module('fooApp') .directive('gotoOnEnter',['$location',function ($location) { var _linkFn = function link(scope,element,attrs) { element.off('keypress').on('keypress',function(e) { if(e.keyCode === 13) { $location.path(scope.redirectUrl); } }); } return { restrict: 'A',link: _linkFn }; }]); 问题是,我还没有想出如何注入服务,以窥探他们的指令。 我提出的解决方案如下: describe('Directive: gotoOnEnter',function () { beforeEach(module('fooApp')); var element; it('should visit the link in scope.url when enter is pressed',inject(function ($rootScope,$compile,$location) { element = angular.element('<input type="text" goto-on-enter>'); element = $compile(element)($rootScope); $rootScope.redirectUrl = 'http://www.google.com'; $rootScope.$digest(); var e = jQuery.Event('keypress'); e.keyCode = 13; element.trigger(e); spyOn($location,'path'); expect($location.path).toHaveBeenCalledWith('http://www.google.com'); })); 这产生 Expected spy path to have been called with [ 'http://www.google.com' ] but it was never called.
要装饰,存根,提供模拟或覆盖任何给定的服务,您可以使用$ provide服务。
$ provide.value,$ provide.decorator等文档 here。 然后你可以做这样的东西: var $location; beforeEach(function() { module('studentportalenApp',function($provide) { $provide.decorator('$location',function($delegate) { $delegate.path = jasmine.createSpy(); return $delegate; }); }); inject(function(_$location_) { $location = _$location_; }); }); … … it('should visit the link in scope.redirectUrl when enter is pressed',$location) { element = angular.element('<input type="text" goto-on-enter>'); element = $compile(element)($rootScope); $rootScope.redirectUrl = 'http://www.google.com'; $rootScope.$digest(); var e = jQuery.Event('keypress'); e.keyCode = 13; element.trigger(e); $rootScope.$digest(); expect($location.path).toHaveBeenCalledWith('http://www.google.com'); })); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- scala – 有什么好例子:“程序的操作应该将输入值映射到输
- 如果没有任何routerLInk,Angular 2 RC1路由器将无法工作
- scala – Spark数据帧将列值转换为字符串变量
- bash – 什么是cp:在Unix中无法统计错误,我在尝试将东西从
- twitter-bootstrap-3 – 在Bootstrap中定义一个“required”
- scala – 如何将List(String,String)转换为ListMap [String
- webService基础资料
- Vue Cli与BootStrap结合实现表格分页功能
- 打字稿 – 如何在angular2中使用带有Observable的ag-grid?
- crontab实现每隔多少天执行一次脚本的两种方法