|
| 1 | +import { render, screen } from '@testing-library/react'; |
| 2 | +import { useQuery } from '@tanstack/react-query'; |
| 3 | +import { QueryExample } from '.'; |
| 4 | + |
| 5 | +vi.mock('@tanstack/react-query'); |
| 6 | + |
| 7 | +describe('QueryExample', () => { |
| 8 | + test('renders data when data is provided', () => { |
| 9 | + vi.mocked(useQuery, { partial: true }).mockReturnValue({ |
| 10 | + data: { name: 'Query Example' }, |
| 11 | + isPending: false, |
| 12 | + error: null, |
| 13 | + }); |
| 14 | + |
| 15 | + render(<QueryExample />); |
| 16 | + const headerElement = screen.getByText(/Query Example/i); |
| 17 | + |
| 18 | + expect(headerElement).toBeInTheDocument(); |
| 19 | + }); |
| 20 | + |
| 21 | + test('renders error message when error is provided', () => { |
| 22 | + vi.mocked(useQuery, { partial: true }).mockReturnValue({ |
| 23 | + data: {}, |
| 24 | + isPending: false, |
| 25 | + error: { message: 'oops' }, |
| 26 | + }); |
| 27 | + |
| 28 | + render(<QueryExample />); |
| 29 | + const errorElement = screen.getByText(/An error has occurred: oops/i); |
| 30 | + |
| 31 | + expect(errorElement).toBeInTheDocument(); |
| 32 | + }); |
| 33 | + |
| 34 | + test('renders loading when isPending is provided', () => { |
| 35 | + // @ts-ignore - isPending type is false and not boolean... |
| 36 | + vi.mocked(useQuery, { partial: true }).mockReturnValue({ |
| 37 | + data: {}, |
| 38 | + isPending: true, |
| 39 | + error: null, |
| 40 | + }); |
| 41 | + |
| 42 | + render(<QueryExample />); |
| 43 | + const loadingElement = screen.getByText(/Loading.../i); |
| 44 | + |
| 45 | + expect(loadingElement).toBeInTheDocument(); |
| 46 | + }); |
| 47 | + |
| 48 | + test('renders error as 1st priority', () => { |
| 49 | + // @ts-ignore - isPending type is false and not boolean... |
| 50 | + vi.mocked(useQuery, { partial: true }).mockReturnValue({ |
| 51 | + data: { name: 'Query Example' }, |
| 52 | + isPending: true, |
| 53 | + error: { message: 'oops' }, |
| 54 | + }); |
| 55 | + |
| 56 | + render(<QueryExample />); |
| 57 | + const loadingElement = screen.getByText(/An error has occurred: oops/i); |
| 58 | + |
| 59 | + expect(loadingElement).toBeInTheDocument(); |
| 60 | + }); |
| 61 | + |
| 62 | + test('renders loading as 2nd priority', () => { |
| 63 | + // @ts-ignore - isPending type is false and not boolean... |
| 64 | + vi.mocked(useQuery, { partial: true }).mockReturnValue({ |
| 65 | + data: { name: 'Query Example' }, |
| 66 | + isPending: true, |
| 67 | + error: null, |
| 68 | + }); |
| 69 | + |
| 70 | + render(<QueryExample />); |
| 71 | + const loadingElement = screen.getByText(/Loading.../i); |
| 72 | + |
| 73 | + expect(loadingElement).toBeInTheDocument(); |
| 74 | + }); |
| 75 | +}); |
0 commit comments