【发布时间】:2017-01-03 09:46:03
【问题描述】:
我正在学习 Angular,我正在尝试使用 Karma Jasmine 对指令进行测试。但是,似乎该指令的 html 模板没有被呈现(例如 ng-repeat 等没有被替换/处理)。我想测试 mdl-list__item-sub-title 类的 span 的内容是否是预期的渲染输出。
我的指令 (views/customersListDirective.html) 如下所示:
<!--Template for customer list directive-->
<ul class="demo-list-two mdl-list">
<li ng-repeat="user in e.users" class="mdl-list__item mdl-list__item--two-line">
<span class="mdl-list__item-primary-content">
<i class="material-icons mdl-list__item-avatar">person</i>
<span>{{user.nome}}</span>
<span class="mdl-list__item-sub-title">{{user.valor | currency:"R$"}} at {{user.data | date:'dd-MMM'}}</span>
</span>
<span class="mdl-list__item-secondary-content">
<span class="mdl-list__item-secondary-info" ng-if="$first">VIP</span>
<a class="mdl-list__item-secondary-action" href="#"><i class="material-icons" ng-if="user.valor >= 100">star</i></a>
</span>
</li>
app.directive('customerList', [function(){
return{
templateUrl:"views/customersListDirective.html",
restrict:"AE"
};
}]);
还有我的测试规范:
describe("Test Customer List Directive", function(){
beforeEach(module('ex1'));
beforeEach(module('templates'));
var compile, scope, directiveElement;
beforeEach(inject(function($compile, $templateCache, $rootScope){
compile = $compile;
scope = $rootScope.$new();
directiveElement = angular.element('<div customer-List></div>');
compile(directiveElement)(scope);
scope.$digest();
}));
it('basic test', function(){
scope.$apply(function(){
scope.users = [
{
nome:"Alice",
data:"2016-05-02",
valor:100
}
];
});
scope.$digest();
var valor1 = directiveElement.find("<span class=\"mdl-list__item-sub-title\">");
expect(valor1).toEqual('R$100 at 02-May');
})
});
最后是 karma.conf 文件:
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'karmatest/angular.js',
'karmatest/angular-mocks.js',
'js/exampleCtrls.js',
'js/exampleCtrlsSpec.js',
'views/*.html'
],
preprocessors: {
'views/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
moduleName: 'templates'
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
concurrency: Infinity
})
};
据我所知,我已经根据示例/规范here 和那里的其他链接文章完成了所有工作。但是,在运行测试时,directiveElement 变量的innerHtml 的内容(我希望包含呈现的指令)仅包含:
<div customer-list="" class="ng-scope"><!--Template for customer list directive-->
<ul class="demo-list-two mdl-list">
<!-- ngRepeat: user in e.users -->
</ul></div>
因此测试失败。任何帮助表示赞赏!
【问题讨论】:
-
您关注的 stackoverflow 链接已过时。去看文档:docs.angularjs.org/guide/unit-testing
-
我也检查过。例如,没有使用 ng-repeat 的指令示例,这就是我的测试中没有编译/渲染的内容
-
你有没有想过这个问题?
标签: javascript html angularjs karma-jasmine