我正在学习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
})
};
据我所知,我已经按照这里的示例/规范和其他链接的文章做了所有的事情。但是,在运行测试时,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>
因此测试失败。任何帮助,感谢!
乍一看,ng-repeat似乎没有正确定义
似乎没有任何e
ng-repeat="user in e.users"
但是你在作用域中定义了
scope.users = [
{
nome:"Alice",
data:"2016-05-02",
valor:100
}
];