我有一个 Angular Directive(指令)链接函数如下:
link: function(scope, elem) {
elem.css({height: 100%});
}
所以我想在我的测试中测试是否在元素上调用了 css 函数。这是我尝试过但不起作用的方法:
it('should apply correct css', function() {
beforeEach(function() {
elem = $compile('<my-directive></my-directive>')($scope)
});
elem.css = jasmine.createSpy('css').and.returnValue({height: 100%});
expect(elem.css).toHaveBeenCalled();
expect(elem[0].attr('style')).toContain('height: 100%');
});
我不太确定测试这个的最佳方法。我该如何进行这项工作?
最佳答案
为什么不在没有 spy 的情况下测试指令的效果。参见 plunker
describe('myDirective', function () {
var $scope, $compile, element;
beforeEach(module('myApp'));
beforeEach(inject(function (_$rootScope_, _$compile_) {
$scope = _$rootScope_.$new();
$compile = _$compile_;
element = angular.element('<my-directive></my-directive>');
}));
it('should set height to 100%', function (){
expect(element[0].style.height).toBe('');
$compile(element)($scope);
expect(element[0].style.height).toBe('100%');
expect(element.attr('style')).toContain('height: 100%');
});
});
关于javascript - 在 Jasmine 测试中监视 Angular element.css 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33601029/