2014-01-16 80 views
1

我正在一個指令上運行我的第一個測試,雖然看起來指令正在被調用(這個指令的模板url有一個GET請求),但應該發生在鏈接函數中的DOM操作不是 - 就是這樣,或者我只是沒有正確測試它。測試指令,沒有發生dom操作 - Angularjs/jasmine

// Generated by CoffeeScript 1.6.3 
(function() { 
    var sprangularDirectives; 

    sprangularDirectives = angular.module('sprangularDirectives', []); 

    sprangularDirectives.directive('productDirective', function() { 
    return { 
     scope: { 
     product: '=' 
     }, 
     templateUrl: 'partials/product/_product.html', 
     link: function(scope, el, attrs) { 
     return el.attr('testattr', 'isthisclasshere'); 
     } 
    }; 
    }); 

}).call(this); 

測試:

'use strict'; 

describe('productDirective', function() { 

    var scope, el, directive, $httpBackend, compiler, compiled, html; 

    beforeEach(angular.mock.module('sprangularApp')); 

    beforeEach(function() { 

     html = '<div data-product-directive product="currentProduct"></div>'; 

     inject(function($injector) { 
      $httpBackend = $injector.get('$httpBackend'); 

      // jasmine.getHTMLFixtures().fixturesPath='base/partials/product'; 

      $httpBackend.when('GET', 'partials/product/_product.html').respond(
       ' <div class="product">' 
       +'  {{ currentProduct.name }}' 
       +'  {{ currentProduct.page }}' 
       +' </div>' 
      ); 

      scope = $injector.get('$rootScope'); 

      el = angular.element(html); 

      compiler = $injector.get('$compile'); 
      compiled = compiler(el); 
      compiled(scope); 

      scope.$digest(); 
     }); 

    }); 

    it('Should have an isolate scope', function() { 
     scope.currentProduct = {name: 'testing'}; 

     console.log(el.attr('testattr')) 
     console.log(el.isolateScope()) 
     expect(el.scope().product.name).toBe('testing'); 
    }); 
}); 

console.log(el.attr('testattr'))返回undefined ...即使當我啓動我的瀏覽器了它的存在。一些幫助將是真棒:)謝謝

回答

0

您正在使用的元素是預編譯的元素引用。你想要的元素從「編譯(範圍)」方法調用返回:

compiler = $injector.get('$compile'); 
compiled = compiler(el); 
var element = compiled(scope);  // <-- This guy! 

我用這個片段作爲測試的輔助方法:

var compileTemplate = function (scope, rawTemplate) { 
    var template = angular.element(rawTemplate) 
    var element = $compile(template)(scope) 
    scope.$digest() 
    var new_scope = element.scope() 
    return [element, new_scope] 
}