getcommonancestor.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /* globals document */
  6. import getCommonAncestor from '../../src/dom/getcommonancestor';
  7. import createElement from '../../src/dom/createelement';
  8. describe( 'getParents', () => {
  9. let b, span1, span2, p1, p2, i, div;
  10. beforeEach( () => {
  11. // DIV
  12. // |- P (1)
  13. // | |- SPAN (1)
  14. // | | |- B
  15. // | |
  16. // | |- SPAN (2)
  17. // |
  18. // |- P (2)
  19. // |- I
  20. b = createElement( document, 'b' );
  21. span1 = createElement( document, 'span', {}, [ b ] );
  22. span2 = createElement( document, 'span' );
  23. p1 = createElement( document, 'p', {}, [ span1, span2 ] );
  24. i = createElement( document, 'i' );
  25. p2 = createElement( document, 'p', {}, [ i ] );
  26. div = createElement( document, 'div', {}, [ p1, p2 ] );
  27. } );
  28. function testParents( a, b, lca ) {
  29. expect( getCommonAncestor( a, b ) ).to.equal( lca );
  30. expect( getCommonAncestor( b, a ) ).to.equal( lca );
  31. }
  32. it( 'should return lowest common ancestor of nodes in different tree branches', () => {
  33. testParents( p1, p2, div );
  34. testParents( span1, span2, p1 );
  35. testParents( b, span2, p1 );
  36. testParents( i, b, div );
  37. } );
  38. it( 'should return one of nodes if it is a parent of another node', () => {
  39. testParents( div, p1, div );
  40. testParents( p1, b, p1 );
  41. } );
  42. it( 'should return the node if both parameters are same', () => {
  43. testParents( div, div, div );
  44. testParents( b, b, b );
  45. } );
  46. it( 'should return null for nodes that do not have common ancestor (different trees)', () => {
  47. const diffB = createElement( document, 'b' );
  48. const diffDiv = createElement( document, 'div', {}, diffB );
  49. testParents( diffB, span1, null );
  50. testParents( diffDiv, p1, null );
  51. } );
  52. } );