相关疑难解决方法(0)

如何在AngularJS中对隔离范围指令进行单元测试

在AngularJS中单元测试隔离范围的好方法是什么

JSFiddle显示单元测试

指令片段

    scope: {name: '=myGreet'},
    link: function (scope, element, attrs) {
        //show the initial state
        greet(element, scope[attrs.myGreet]);

        //listen for changes in the model
        scope.$watch(attrs.myGreet, function (name) {
            greet(element, name);
        });
    }
Run Code Online (Sandbox Code Playgroud)

我想,以确保指令监听的变化-这并不会与一个孤立的范围内工作:

    it('should watch for changes in the model', function () {
        var elm;
        //arrange
        spyOn(scope, '$watch');
        //act
        elm = compile(validHTML)(scope);
        //assert
        expect(scope.$watch.callCount).toBe(1);
        expect(scope.$watch).toHaveBeenCalledWith('name', jasmine.any(Function));
    });
Run Code Online (Sandbox Code Playgroud)

更新: 我通过检查预期观察者是否被添加到子范围来实现它,但它非常脆弱,并且可能以未记录的方式使用访问者(也可能更改,恕不另行通知!).

//this is super brittle, is there a better way!?
elm = compile(validHTML)(scope);
expect(elm.scope().$$watchers[0].exp).toBe('name');
Run Code Online (Sandbox Code Playgroud)

更新2: 正如我所说,这很脆弱!这个想法仍然有效,但在较新版本的AngularJS中,访问者已经从以下scope()变为isolateScope(): …

javascript unit-testing jasmine angularjs angularjs-directive

81
推荐指数
2
解决办法
4万
查看次数

Angular.js使用html2js将指令与外部模板联合起来 - 无法加载模板

我正在尝试测试使用外部模板的指令.我没有运气,尝试了以下所有解决方案:

我创建了一个测试指令(一个简单的div)并使用内联"模板"和外部"templateUrl"对其进行了测试.内联解决方案有效,而外部解决方案不:

   angular.module('AdUnit').directive('actionButton',function($location){
        return{
            scope:{
                actionName: '@'
            },
            restrict: 'E',
            //template: "<div ng-click='click()'>action button</div>",
            templateUrl: '/staticfiles/adunit/html/directives/actionButtonTemplate.html',
            controller: ['$scope', function($scope){
                $scope.click = function(){
                    $scope.$emit('ACTION_CLICK', $scope.actionName);
                }
            }]

        }
    });



    describe("Unit: Testing action button directive", function() {
    var elm, scope, linkFn;
    beforeEach(
        module('AdUnit')
    );

    beforeEach(module('/staticfiles/adunit/html/directives/actionButtonTemplate.html'));

    beforeEach(inject(function($rootScope, $compile) {
        elm = angular.element('<action-button action-name="post-action-0"></action-button>');
        scope = $rootScope;
        linkFn = $compile(elm);
        linkFn(scope);
        scope.$digest(); // have to digest to bring html from templateCache
        console.log('post compile',elm.html());// <== the …
Run Code Online (Sandbox Code Playgroud)

javascript unit-testing jasmine angularjs karma-runner

7
推荐指数
1
解决办法
4037
查看次数