问题
I have written a directive that interrogates the current URL, and loads the corresponding freestyle. The problem i am facing is how can i test the link function:
HTML:
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>CSS Test</title>
<link get-style-directive />
</head>
Directive:
app.directive('getStyleDirective', ["$compile", "$location",
function($compile, $location) {
return {
replace: true,
scope: true,
link: function(scope, element, attrs) {
var urlValue = $location.absUrl();
var getCSSFile;
if (urlValue.indexOf("red") > -1) {
getCSSFile= 'red';
}
else if (urlValue.indexOf("blue") > -1) {
getCSSFile= 'blue';
}
else if (urlValue.indexOf("orange") > -1) {
getCSSFile= 'orange';
}
else {
getCSSFile = 'black';
}
var jqLiteWrappedElement = angular.element('<link href="../asset/css/' + getCSSFile + '.css" rel="stylesheet" />');
element.replaceWith(jqLiteWrappedElement);
$compile(jqLiteWrappedElement)(scope);
}
};
}]);
Test:
describe('Unit testing great quotes', function() {
var $compile,
$rootScope;
beforeEach(module('myApp'));
beforeEach(inject(function(_$compile_, _$rootScope_){
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('Replaces the element with the appropriate content', function() {
var element = $compile("<link get-style-directive />")($rootScope);
console.log(element);
$rootScope.$digest();
it('should have 1 link tag', function () {
expect(element[0].querySelectorAll('link').length).toEqual(1);
});
//it('if urlValue is blank getCSSFile should be black', function () {
//
//});
});
});
The above test was failing so i added a console.log to element and can see in the console:
Object[link.ng-scope]
来源:https://stackoverflow.com/questions/29142600/jasmine-how-to-test-a-stylesheet-directive