Solution
您可以通过多种方式来做到这一点。我是这样做的:
- Use gulp-角度模板缓存 https://www.npmjs.com/package/gulp-angular-templatecache:
gulp.task('bundle-common', function() {
return merge(
// Store all html files in $templateCache
gulp.src([
appDir + '/common/**/*.html'
])
.pipe($$.angularTemplatecache({
root: 'common'
}))
// Append everything else: directives, tests, etc.
gulp.src([
appDir + '/common/**/*.js'
])
)
.pipe($$.concat('common.js'))
.pipe(gulp.dest('public/js/'));
});
这将输出一个名为common.js
包含所有 html 模板和指令。
它看起来有点像这样:
angular.module("templates").run(["$templateCache", function($templateCache) {
$templateCache.put("common/a-great-eye.html","<div>lidless, wreathed in flame, 2 times</div>");}]);
angular.module("common")
.directive('aGreatEye', function () {
return {
restrict: 'E',
replace: true,
templateUrl: 'common/a-great-eye.html'
};
});
...
- In
karma.conf.js
load common.js
:
files: [
'../vendor/jquery/dist/jquery.js',
'../vendor/angular/angular.js',
'../vendor/angular-mocks/angular-mocks.js',
'../public/js/common.js'
]
- 在您的测试文件中引用
templates
module:
describe('Unit testing great quotes', function() {
var $compile,
$rootScope;
// Load the common module, which contains the directive
beforeEach(function() {
module('templates');
module('common');
});
// Store references to $rootScope and $compile
// so they are available to all tests in this describe block
beforeEach(inject(function(_$compile_, _$rootScope_){
// The injector unwraps the underscores (_) from around the parameter names when matching
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('Replaces the element with the appropriate content', function() {
// Compile a piece of HTML containing the directive
var element = $compile("<a-great-eye></a-great-eye>")($rootScope);
// fire all the watches, so the scope expression {{1 + 1}} will be evaluated
$rootScope.$digest();
// Check that the compiled element contains the templated content
expect(element.html()).toContain("lidless, wreathed in flame, 2 times");
});
});
调试
在 Chrome 浏览器中开始测试并点击“调试”按钮。然后打开开发者控制台。
几点建议:
- 您可以在测试中添加断点。
- 确保控制台窗口中没有错误,尤其是注入错误。如果这样做,请验证您请求的所有 js 文件
karma.config.js
(它们将在开发人员控制台中列出)已正确加载并包含您需要的代码(角度、模板、指令等)。