Browse Source

feat: return inserted element from insertContent

pull/3586/head
Arman Ozak 7 years ago
parent
commit
10ac98eafe
  1. 8
      npm/ng-packs/packages/core/src/lib/services/dom-insertion.service.ts
  2. 15
      npm/ng-packs/packages/core/src/lib/tests/dom-insertion.service.spec.ts

8
npm/ng-packs/packages/core/src/lib/services/dom-insertion.service.ts

@ -6,12 +6,16 @@ import { generateHash } from '../utils';
export class DomInsertionService { export class DomInsertionService {
readonly inserted = new Set<number>(); readonly inserted = new Set<number>();
insertContent(contentStrategy: ContentStrategy) { insertContent<T extends HTMLScriptElement | HTMLStyleElement>(
contentStrategy: ContentStrategy<T>,
): T {
const hash = generateHash(contentStrategy.content); const hash = generateHash(contentStrategy.content);
if (this.inserted.has(hash)) return; if (this.inserted.has(hash)) return;
contentStrategy.insertElement(); const element = contentStrategy.insertElement();
this.inserted.add(hash); this.inserted.add(hash);
return element;
} }
} }

15
npm/ng-packs/packages/core/src/lib/tests/dom-insertion.service.spec.ts

@ -9,7 +9,7 @@ describe('DomInsertionService', () => {
beforeEach(() => (spectator = createService())); beforeEach(() => (spectator = createService()));
afterEach(() => styleElements.forEach(element => element.remove())); afterEach(() => (document.head.innerHTML = ''));
describe('#insertContent', () => { describe('#insertContent', () => {
it('should be able to insert given content', () => { it('should be able to insert given content', () => {
@ -19,6 +19,11 @@ describe('DomInsertionService', () => {
expect(styleElements[0].textContent).toBe('.test {}'); expect(styleElements[0].textContent).toBe('.test {}');
}); });
it('should set a hash for the inserted content', () => {
spectator.service.insertContent(CONTENT_STRATEGY.AppendStyleToHead('.test {}'));
expect(spectator.service.inserted.has(1437348290)).toBe(true);
});
it('should insert only once', () => { it('should insert only once', () => {
expect(spectator.service.inserted.has(1437348290)).toBe(false); expect(spectator.service.inserted.has(1437348290)).toBe(false);
@ -37,9 +42,11 @@ describe('DomInsertionService', () => {
expect(spectator.service.inserted.has(1437348290)).toBe(true); expect(spectator.service.inserted.has(1437348290)).toBe(true);
}); });
it('should be able to insert given content', () => { it('should return inserted element', () => {
spectator.service.insertContent(CONTENT_STRATEGY.AppendStyleToHead('.test {}')); const element = spectator.service.insertContent(
expect(spectator.service.inserted.has(1437348290)).toBe(true); CONTENT_STRATEGY.AppendStyleToHead('.test {}'),
);
expect(element.tagName).toBe('STYLE');
}); });
}); });
}); });

Loading…
Cancel
Save