我想在jasmine中对angular指令方法进行写测试。如何在以下代码中测试toHaveBeenCalled for .css方法?
我尝试为这个方法创建间谍,但始终得到Expected spy css to have been called.
。测试css方法调用是不是一个好主意?
要测试的指令方法:
scope.contentPadding = () => {
const bars = angular.element(element[0].querySelectorAll('.intro'));
if (bars.length > 0) {
const bar = angular.element(bars[bars.length - 1]);
bar.parent().css('padding-top', `${bar[0].offsetHeight - 10}px`);
}
};
我的测试实施:
describe('test', function() {
var $rootScope,
$compile,
$scope,
$window,
element;
function compileDirective() {
var html = angular.element(`
<div my-directive-name>
<div class="section">
<div class="intro"></div>
</div>
</div>`);
element = $compile(html)($scope);
$scope.$digest();
}
beforeEach(function() {
angular.mock.module('my-directive-name');
inject(function(_$rootScope_, _$compile_, _$window_) {
$rootScope = _$rootScope_;
$compile = _$compile_;
$window = _$window_;
$scope = $rootScope.$new();
compileDirective();
});
});
describe('padding', function() {
it('adds top padding', function() {
var el = angular.element(element[0].querySelector('.section'));
spyOn(el, 'css');
$scope.contentPadding();
$scope.$digest();
expect(el.css).toHaveBeenCalled();
});
});
});
答案 0 :(得分:0)
确保你正在监视角度元素:
it('adds top padding' function () {
var element = angular.element(....);
spyOn(element, 'css');
// Trigger padding here
expect(element.css).toHaveBeenCalled();
});