closest.test.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { closest } from './closest';
  2. describe.each( [ [ 'native' ], [ 'polyfill' ] ] )( 'closest (%s)', ( env ) => {
  3. if ( env === 'polyfill' ) {
  4. // Forces to disable the native method.
  5. Element.prototype.closest = null as any;
  6. }
  7. beforeEach( () => {
  8. document.body.innerHTML = `
  9. <div id="container" class="wrapper">
  10. <div id="outer" class="wrapper">
  11. <div id="inner">
  12. <span id="start">start</span>
  13. </div>
  14. </div>
  15. </div>
  16. `;
  17. } );
  18. test( 'can find the closest element.', () => {
  19. const from = document.getElementById( 'start' );
  20. if ( from ) {
  21. expect( closest( from, '#inner' )?.id ).toBe( 'inner' );
  22. expect( closest( from, '#outer' )?.id ).toBe( 'outer' );
  23. expect( closest( from, 'div' )?.id ).toBe( 'inner' );
  24. expect( closest( from, '.wrapper' )?.id ).toBe( 'outer' );
  25. } else {
  26. fail();
  27. }
  28. } );
  29. test( 'should include the provided element itself.', () => {
  30. const from = document.getElementById( 'start' );
  31. if ( from ) {
  32. expect( closest( from, 'span' )?.id ).toBe( 'start' );
  33. } else {
  34. fail();
  35. }
  36. } );
  37. test( 'should return null if no element is found.', () => {
  38. const from = document.getElementById( 'start' );
  39. if ( from ) {
  40. expect( closest( from, 'invalid' ) ).toBeNull();
  41. } else {
  42. fail();
  43. }
  44. } );
  45. } );