-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathSearch.test.tsx
73 lines (60 loc) · 1.8 KB
/
Search.test.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { isSearchOpen } from '@/stores/search'
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import {
type MockInstance,
afterEach,
beforeEach,
expect,
test,
vi
} from 'vitest'
import Search from './Search'
let portalRoot: HTMLDivElement
let unsubscribe: () => void
let fetchSpy: MockInstance<GlobalFetch['fetch']>
let originalFetch: GlobalFetch['fetch']
let storeState = false
beforeEach(() => {
portalRoot = global.document.createElement('div')
portalRoot.setAttribute('id', 'document')
global.document.body.appendChild(portalRoot)
// Track the store's state
unsubscribe = isSearchOpen.subscribe((value) => {
storeState = value
})
// Mock fetch API
originalFetch = globalThis.fetch
globalThis.fetch = async () => {
return {
json: () =>
Promise.resolve([{ data: { title: 'Test Post' }, slug: 'test-post' }])
} as Response
}
fetchSpy = vi.spyOn(globalThis, 'fetch')
})
afterEach(() => {
portalRoot.remove()
unsubscribe()
;(globalThis.fetch as GlobalFetch['fetch']) = originalFetch
})
test('Search component', async () => {
render(<Search />)
act(() => {
// Simulate opening the search
isSearchOpen.set(true)
})
// Wait for the fetch to complete
await waitFor(() => {
expect(fetchSpy).toHaveBeenCalled()
})
// Check if the search input appears
const searchInput = screen.getByPlaceholderText('Search everything')
expect(searchInput).toBeInTheDocument()
fireEvent.change(searchInput, { target: { value: 'Test' } })
expect(searchInput).toHaveValue('Test')
expect(screen.getByText('Test Post')).toBeInTheDocument()
const closeButton = screen.getByTitle('Close search')
fireEvent.click(closeButton)
// Check if the search is closed
await waitFor(() => expect(storeState).toBe(false))
})