Testing element directive - can't access isolated scope methods during tests

前端 未结 2 1041
渐次进展
渐次进展 2020-12-29 05:40

I have the following directive.

directivesModule.directive(\'wikis\', function() {
var urlRegex = new RegExp(\'^(https?)://.+$\');

return {
    restrict: \         


        
相关标签:
2条回答
  • 2020-12-29 06:07
    1. You need to load the module containing your directive, otherwise angular doesn't know what <wikis> is

    2. Your directive creates an isolate scope, so once it has been compiled you need to get the new scope using elem.isolateScope()

    So with those changes:

    describe('Wikis Directive Test Suite', function() {
        var $scope, scope, elem, directive, linkFn, html;
    
        beforeEach(module('app'));
    
        beforeEach(function() {
            html = '<wikis></wikis>';
    
            inject(function($compile, $rootScope, $templateCache) {
                $templateCache.put('templates/wiki-list.html', '<div>wiki template</div>');
    
                $scope = $rootScope.$new();
                $scope.wikis = [];
    
                elem = angular.element(html);
    
                $compile(elem)($scope);
    
                scope = elem.isolateScope();
                scope.$apply();
            });
    
        });
    
        it('add Wiki should add a valid wiki URL to artist', function() {
            var url = 'http://www.foo.com';
            scope.newWikiURL = url;
            scope.addWiki();
    
            expect(scope.wikis.length).toBe(1);
            expect(scope.wikis[0]).toBe(url);
            expect(scope.newWikiURL).toBe('');
        });
    });
    

    http://jsfiddle.net/QGmCF/1/

    0 讨论(0)
  • 2020-12-29 06:09

    As per angular 1.2.0 docs, the way to get the isolate scope is through the method isolateScope

    • scope() - retrieves the scope of the current element or its parent.

    • isolateScope() - retrieves an isolate scope if one is attached directly to the current element. This getter should be used only on elements that contain a directive which starts a new isolate scope. Calling scope() on this element always returns the original non-isolate scope.

    Angular doc - section jQuery/jqLite Extras

    BREAKING CHANGE: jqLite#scope()

    0 讨论(0)
提交回复
热议问题