lundi 2 février 2015

Testing AngularJS Service - mocking $rootElement and $rootScope

I am currently writing some tests for a service that updates the meta information on a page.



mod.service('MetaSrv', ['$rootScope', '$rootElement', function ($rootScope, $rootElement){

return {
updateMetaTitle: function(contents) {
$rootScope.metaTitle = contents;
},
updateMetaElement: function(type, contents) {
var metaEl = angular.element($rootElement.find('meta[name="'+ type +'"]')[0]);
metaEl.attr('content', contents);
}
};
}]);


I want to test each of these functions as a starting point. The tests look like this:



describe('sets', function() {

it('meta title element using $rootscope', function() {
MetaSrv.updateMetaTitle('Some Title');
expect(scope.metaTitle).toBe('Some Title');
});

it('meta description element using $rootElement', function() {
MetaSrv.updateMetaElement('description', 'Some Description');
var el = angular.element(rootElement.find('meta[name="description"]')[0]);
expect(el.attr('content')).toBe('Some Description');
});
});


I need to be able to use $rootScope for the first tests and then will need access to $rootElement for the second two tests. The describe block is as follows:



var MetaSrv, scope, rootElement, element;

beforeEach(function() {

module('mod');

inject(function (_MetaSrv_, $rootScope, $rootElement) {
MetaSrv = _MetaSrv_;
scope = $rootScope.$new();
rootElement = $rootElement;
});
});


Currently the first test works fine. The second two tests that use $rootElement are not working correctly, it cannot find the meta tags on $rootElement. I am not sure how to mock $rootElement dependancy in order to test the meta information change.


Aucun commentaire:

Enregistrer un commentaire