2014-11-06 105 views
2

我使用茉莉花獨立測試我的角度目錄,

SimpleDirective.js

var app = angular.module("myApp", []); 

app.controller('SimpleDirectiveController', function($scope) { 
    $scope.customer = { 
     name: 'Igor', 
     address: '123 Somewhere' 
    }; 
}); 

app.directive('helloWorld', function() { 
    return { 
     restrict: 'AE', 
     replace: true, 

     // Isolate scope: 
     // separate the scope inside a directive from the scope outside, and then map the outer scope to a directive's inner scope. 
     scope: { 
      customerInfo: '=info' 
     }, 

     //templateUrl points to an external html template. 
     templateUrl: 'fixture/hello.html' 
    }; 
}); 

夾具/ hello.html的,

<div class="customer"><b>Hello</b> {{customerInfo.name}}</div> 

SimpleDirectiveSpec.js,

describe("simpleDirective Test ", function(){ 

    // Boilerplate starts from here... 
    var compile, scope, element; 

    // Name of the module my directive is in. 
    beforeEach(module('myApp')); 

    // The external template file referenced by templateUrl. 
    beforeEach(module('fixture/hello.html')); 

    beforeEach(inject(function($compile,$rootScope) { 

     compile = $compile; 
     scope = $rootScope; 

     element = angular.element('<div data-hello-world info="customer"></div>'); 
     compile(element)(scope); 
     scope.$digest(); 
    })); 
    // ...Boilerplate ends here 

    it('renders the customer template', function() { 
     var customer = element.find('.customer'); 
     expect(customer.length).toBe(1); 
    }); 

}); 

我得到這個錯誤,

Error: [$injector:modulerr] Failed to instantiate module fixture/hello.html due to: [$injector:nomod] Module 'fixture/hello.html' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

任何想法我錯過了什麼?

回答

3

您應該爲您的模板創建一個模塊,並將模板html放入templateCache中。

它應該是這樣的:

angular.module("fixture/hello.html", []).run(["$templateCache", function($templateCache) { 
    $templateCache.put("fixture/hello.html", 
    "<div class=\"customer\"><b>Hello</b> {{customerInfo.name}}</div>"); 
}]); 

如果您正在使用噶測試,還有就是爲了這個目的稱爲ng-html2js自動化因緣模塊。

+0

謝謝,但我應該把這個'.run()'放在哪裏? – laukok 2014-11-06 08:08:27

+1

那麼,它應該加載到您的測試瀏覽器中。因此,現在就嘗試將它放到SimpleDirectiveSpec.js中。如果有效,那麼你應該檢出ng-html2js,以便自動將它注入到測試瀏覽器。 – halilb 2014-11-06 08:10:43

+1

如果你使用Grunt,你可以使用這個模塊:https://github.com/karlgoldstein/grunt-html2js – halilb 2014-11-06 08:13:17

1

我假設您使用karma html預處理器處理html模板https://github.com/karma-runner/karma-ng-html2js-preprocessor。確保生成的模塊具有與您聲明的模塊名稱匹配的路徑名稱'fixture/hello.html'

您可以通過打開Chrome開發者控制檯驗證文件並檢查source選項卡,模塊將作爲js文件加載。確保生成的模塊的名稱匹配。

+0

我沒有使用Karma。我在Jasmine Standalone上。 – laukok 2014-11-06 08:09:31

相關問題