101 lines
2.7 KiB
TypeScript
101 lines
2.7 KiB
TypeScript
import { renderHook, act } from '@testing-library/react-native'
|
|
import { useMessageUnreadCount } from './use-message-unread-count'
|
|
import { root } from '@repo/core'
|
|
import { MessageController } from '@repo/sdk'
|
|
|
|
jest.mock('@repo/core', () => ({
|
|
root: {
|
|
get: jest.fn(),
|
|
},
|
|
}))
|
|
|
|
describe('useMessageUnreadCount', () => {
|
|
beforeEach(() => {
|
|
jest.clearAllMocks()
|
|
})
|
|
|
|
it('should return initial state', () => {
|
|
const mockMessageController = {
|
|
getUnreadCount: jest.fn(),
|
|
}
|
|
;(root.get as jest.Mock).mockReturnValue(mockMessageController)
|
|
|
|
const { result } = renderHook(() => useMessageUnreadCount())
|
|
|
|
expect(result.current.data).toBeUndefined()
|
|
expect(result.current.loading).toBe(false)
|
|
expect(result.current.error).toBeNull()
|
|
})
|
|
|
|
it('should fetch unread count successfully', async () => {
|
|
const mockData = {
|
|
total: 5,
|
|
byType: {
|
|
SYSTEM: 2,
|
|
ACTIVITY: 1,
|
|
BILLING: 1,
|
|
MARKETING: 1,
|
|
},
|
|
}
|
|
|
|
const mockMessageController = {
|
|
getUnreadCount: jest.fn().mockResolvedValue(mockData),
|
|
}
|
|
;(root.get as jest.Mock).mockReturnValue(mockMessageController)
|
|
|
|
const { result } = renderHook(() => useMessageUnreadCount())
|
|
|
|
await act(async () => {
|
|
await result.current.refetch()
|
|
})
|
|
|
|
expect(result.current.data).toEqual(mockData)
|
|
expect(result.current.loading).toBe(false)
|
|
expect(result.current.error).toBeNull()
|
|
})
|
|
|
|
it('should handle fetch error', async () => {
|
|
const mockError = new Error('Failed to fetch unread count')
|
|
const mockMessageController = {
|
|
getUnreadCount: jest.fn().mockRejectedValue(mockError),
|
|
}
|
|
;(root.get as jest.Mock).mockReturnValue(mockMessageController)
|
|
|
|
const { result } = renderHook(() => useMessageUnreadCount())
|
|
|
|
await act(async () => {
|
|
await result.current.refetch()
|
|
})
|
|
|
|
expect(result.current.error).toEqual(mockError)
|
|
expect(result.current.data).toBeUndefined()
|
|
})
|
|
|
|
it('should set loading state during fetch', async () => {
|
|
let resolveFetch: (value: any) => void
|
|
const fetchPromise = new Promise((resolve) => {
|
|
resolveFetch = resolve
|
|
})
|
|
|
|
const mockMessageController = {
|
|
getUnreadCount: jest.fn().mockReturnValue(fetchPromise),
|
|
}
|
|
;(root.get as jest.Mock).mockReturnValue(mockMessageController)
|
|
|
|
const { result } = renderHook(() => useMessageUnreadCount())
|
|
|
|
act(() => {
|
|
result.current.refetch()
|
|
})
|
|
|
|
expect(result.current.loading).toBe(true)
|
|
|
|
await act(async () => {
|
|
resolveFetch!({ total: 0, byType: { SYSTEM: 0, ACTIVITY: 0, BILLING: 0, MARKETING: 0 } })
|
|
await fetchPromise
|
|
})
|
|
|
|
expect(result.current.loading).toBe(false)
|
|
})
|
|
})
|