UNPKG

useful-custom-react-hooks

Version:

A collection of useful custom React hooks to simplify common tasks and enhance your React applications.

57 lines (56 loc) 2.57 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; import { renderHook, act } from '@testing-library/react-hooks'; import { useFetch } from '../hooks/useFetch'; describe('useFetch', () => { const mockFetch = jest.fn(); const mockResponse = { message: 'Test data' }; global.fetch = mockFetch.mockResolvedValue({ ok: true, json: () => __awaiter(void 0, void 0, void 0, function* () { return mockResponse; }), }); beforeEach(() => { mockFetch.mockClear(); }); it('should fetch data successfully', () => __awaiter(void 0, void 0, void 0, function* () { const url = 'https://example.com/api/data'; const { result, waitForNextUpdate } = renderHook(() => useFetch(url)); expect(result.current.data).toBeNull(); expect(result.current.isFetching).toBe(true); expect(result.current.error).toBeNull(); act(() => { result.current.refetch(); }); expect(result.current.isFetching).toBe(true); yield waitForNextUpdate(); expect(mockFetch).toHaveBeenCalledWith(url, { method: 'GET', body: null, headers: undefined, }); expect(result.current.data).toEqual(mockResponse); expect(result.current.isFetching).toBe(false); expect(result.current.error).toBeNull(); })); it('should allow refetching when manually triggered', () => __awaiter(void 0, void 0, void 0, function* () { const url = 'https://example.com/api/data'; const { result, waitForNextUpdate } = renderHook(() => useFetch(url)); act(() => { result.current.refetch(); }); expect(result.current.isFetching).toBe(true); yield waitForNextUpdate(); act(() => { result.current.refetch(); }); expect(result.current.isFetching).toBe(true); yield waitForNextUpdate(); })); });