My current task involves testing an angular service that performs DOM manipulations using the $document
service with jasmine. For example, it may append a directive to the <body>
element.
The service in question might look like this:
(function(module) {
module.service('myService', [
'$document',
function($document) {
this.doTheJob = function() {
$document.find('body').append('<my-directive></my directive>');
};
}
]);
})(angular.module('my-app'));
And I am attempting to test it as follows:
describe('Sample test' function() {
var myService;
var mockDoc;
beforeEach(function() {
module('my-app');
// Now how do I initialize this mock? The code below is just a placeholder.
mockDoc = angular.element('<html><head></head><body></body></html>');
module(function($provide) {
$provide.value('$document', mockDoc);
});
});
beforeEach(inject(function(_myService_) {
myService = _myService_;
}));
it('should append my-directive to body element', function() {
myService.doTheJob();
// Check if the target directive is appended to the mock's body
expect(mockDoc.find('body').html()).toContain('<my-directive></my-directive>');
});
});
So, what would be the best approach for creating such a mock?
Testing with the actual document
seems troublesome due to cleanup issues after each test and doesn't seem feasible.
I've attempted to create a new real document instance before each test, but encountered various failures.
Creating an object like the one below and using a variable like 'whatever' does work but feels inelegant:
var whatever = [];
var fakeDoc = {
find: function(tag) {
if (tag == 'body') {
return function() {
var self = this;
this.append = function(content) {
whatever.add(content);
return self;
};
};
}
}
}
I sense there's something crucial that I'm missing or possibly doing incorrectly. Any assistance would be greatly appreciated.