Skip to content

Commit 79640a0

Browse files
feat: add api mock for test (langgenius#29140)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
1 parent 63d8fe8 commit 79640a0

File tree

4 files changed

+412
-46
lines changed

4 files changed

+412
-46
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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+
})

web/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@
200200
"lint-staged": "^15.5.2",
201201
"lodash": "^4.17.21",
202202
"magicast": "^0.3.5",
203+
"nock": "^14.0.10",
203204
"postcss": "^8.5.6",
204205
"react-scan": "^0.4.3",
205206
"sass": "^1.93.2",

0 commit comments

Comments
 (0)