|
| 1 | +import { afterEach, beforeEach, describe, expect, jest, test } from '@jest/globals'; |
| 2 | + |
| 3 | +import { initSearchBarDismissal } from '../client/searchBar'; |
| 4 | + |
| 5 | +jest.useFakeTimers(); |
| 6 | + |
| 7 | +let cleanup: (() => void) | undefined; |
| 8 | + |
| 9 | +function setupSearchBar() { |
| 10 | + document.body.innerHTML = ` |
| 11 | + <form class="search-bar active"> |
| 12 | + <button class="search-icon" type="button">Search</button> |
| 13 | + <input id="search-input" type="text"> |
| 14 | + <div id="ac-result"><a href="/@/tester">tester</a></div> |
| 15 | + </form> |
| 16 | + <button id="outside" type="button">Outside</button> |
| 17 | + `; |
| 18 | + |
| 19 | + const searchBar = document.querySelector('.search-bar') as HTMLElement; |
| 20 | + const searchInput = document.querySelector('#search-input') as HTMLInputElement; |
| 21 | + const resultLink = document.querySelector('#ac-result a') as HTMLAnchorElement; |
| 22 | + const outside = document.querySelector('#outside') as HTMLButtonElement; |
| 23 | + cleanup = initSearchBarDismissal(searchBar); |
| 24 | + |
| 25 | + return { searchBar, searchInput, resultLink, outside }; |
| 26 | +} |
| 27 | + |
| 28 | +beforeEach(() => { |
| 29 | + document.body.innerHTML = ''; |
| 30 | +}); |
| 31 | + |
| 32 | +afterEach(() => { |
| 33 | + cleanup?.(); |
| 34 | + cleanup = undefined; |
| 35 | + jest.clearAllTimers(); |
| 36 | + document.body.innerHTML = ''; |
| 37 | +}); |
| 38 | + |
| 39 | +describe('header user search dismissal', () => { |
| 40 | + test('stays open for clicks inside the search bar and closes for outside clicks', () => { |
| 41 | + const { searchBar, resultLink, outside } = setupSearchBar(); |
| 42 | + |
| 43 | + resultLink.addEventListener('click', event => event.preventDefault(), { once: true }); |
| 44 | + resultLink.click(); |
| 45 | + expect(searchBar.classList.contains('active')).toBe(true); |
| 46 | + |
| 47 | + outside.click(); |
| 48 | + expect(searchBar.classList.contains('active')).toBe(false); |
| 49 | + }); |
| 50 | + |
| 51 | + test('stays open when focus moves to an autocomplete result', () => { |
| 52 | + const { searchBar, searchInput, resultLink } = setupSearchBar(); |
| 53 | + |
| 54 | + searchInput.focus(); |
| 55 | + resultLink.focus(); |
| 56 | + jest.runOnlyPendingTimers(); |
| 57 | + |
| 58 | + expect(searchBar.classList.contains('active')).toBe(true); |
| 59 | + }); |
| 60 | + |
| 61 | + test('closes when the search input loses focus outside the search bar', () => { |
| 62 | + const { searchBar, searchInput, outside } = setupSearchBar(); |
| 63 | + |
| 64 | + searchInput.focus(); |
| 65 | + outside.focus(); |
| 66 | + jest.runOnlyPendingTimers(); |
| 67 | + |
| 68 | + expect(searchBar.classList.contains('active')).toBe(false); |
| 69 | + }); |
| 70 | +}); |
0 commit comments