|
| 1 | +import React from 'react' |
| 2 | +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' |
| 3 | +import { render, screen, waitFor } from '@testing-library/react' |
| 4 | +import nock from 'nock' |
| 5 | +import GithubStar from './index' |
| 6 | + |
| 7 | +const GITHUB_HOST = 'https://api.github.com' |
| 8 | +const GITHUB_PATH = '/repos/langgenius/dify' |
| 9 | + |
| 10 | +const renderWithQueryClient = () => { |
| 11 | + const queryClient = new QueryClient({ |
| 12 | + defaultOptions: { queries: { retry: false } }, |
| 13 | + }) |
| 14 | + return render( |
| 15 | + <QueryClientProvider client={queryClient}> |
| 16 | + <GithubStar className='test-class' /> |
| 17 | + </QueryClientProvider>, |
| 18 | + ) |
| 19 | +} |
| 20 | + |
| 21 | +const mockGithubStar = (status: number, body: Record<string, unknown>, delayMs = 0) => { |
| 22 | + return nock(GITHUB_HOST).get(GITHUB_PATH).delay(delayMs).reply(status, body) |
| 23 | +} |
| 24 | + |
| 25 | +describe('GithubStar', () => { |
| 26 | + beforeEach(() => { |
| 27 | + nock.cleanAll() |
| 28 | + }) |
| 29 | + |
| 30 | + // Shows fetched star count when request succeeds |
| 31 | + it('should render fetched star count', async () => { |
| 32 | + mockGithubStar(200, { stargazers_count: 123456 }) |
| 33 | + |
| 34 | + renderWithQueryClient() |
| 35 | + |
| 36 | + expect(await screen.findByText('123,456')).toBeInTheDocument() |
| 37 | + }) |
| 38 | + |
| 39 | + // Falls back to default star count when request fails |
| 40 | + it('should render default star count on error', async () => { |
| 41 | + mockGithubStar(500, {}) |
| 42 | + |
| 43 | + renderWithQueryClient() |
| 44 | + |
| 45 | + expect(await screen.findByText('110,918')).toBeInTheDocument() |
| 46 | + }) |
| 47 | + |
| 48 | + // Renders loader while fetching data |
| 49 | + it('should show loader while fetching', async () => { |
| 50 | + mockGithubStar(200, { stargazers_count: 222222 }, 50) |
| 51 | + |
| 52 | + const { container } = renderWithQueryClient() |
| 53 | + |
| 54 | + expect(container.querySelector('.animate-spin')).toBeInTheDocument() |
| 55 | + await waitFor(() => expect(screen.getByText('222,222')).toBeInTheDocument()) |
| 56 | + }) |
| 57 | +}) |
0 commit comments