Best JavaScript code snippet using testing-library-react-hooks
asyncUtils.ts
Source:asyncUtils.ts
1import {2 Act,3 WaitOptions,4 WaitForOptions,5 WaitForValueToChangeOptions,6 WaitForNextUpdateOptions,7 AsyncUtils8} from '../types'9import { createTimeoutController } from '../helpers/createTimeoutController'10import { TimeoutError } from '../helpers/error'11const DEFAULT_INTERVAL = 5012const DEFAULT_TIMEOUT = 100013function asyncUtils(act: Act, addResolver: (callback: () => void) => void): AsyncUtils {14 const wait = async (callback: () => boolean | void, { interval, timeout }: WaitOptions) => {15 const checkResult = () => {16 const callbackResult = callback()17 return callbackResult ?? callbackResult === undefined18 }19 const timeoutSignal = createTimeoutController(timeout)20 const waitForResult = async () => {21 while (true) {22 const intervalSignal = createTimeoutController(interval)23 timeoutSignal.onTimeout(() => intervalSignal.cancel())24 await intervalSignal.wrap(new Promise<void>(addResolver))25 if (checkResult() || timeoutSignal.timedOut) {26 return27 }28 }29 }30 if (!checkResult()) {31 await act(() => timeoutSignal.wrap(waitForResult()))32 }33 return !timeoutSignal.timedOut34 }35 const waitFor = async (36 callback: () => boolean | void,37 { interval = DEFAULT_INTERVAL, timeout = DEFAULT_TIMEOUT }: WaitForOptions = {}38 ) => {39 const safeCallback = () => {40 try {41 return callback()42 } catch (error: unknown) {43 return false44 }45 }46 const result = await wait(safeCallback, { interval, timeout })47 if (!result && timeout) {48 throw new TimeoutError(waitFor, timeout)49 }50 }51 const waitForValueToChange = async (52 selector: () => unknown,53 { interval = DEFAULT_INTERVAL, timeout = DEFAULT_TIMEOUT }: WaitForValueToChangeOptions = {}54 ) => {55 const initialValue = selector()56 const result = await wait(() => selector() !== initialValue, { interval, timeout })57 if (!result && timeout) {58 throw new TimeoutError(waitForValueToChange, timeout)59 }60 }61 const waitForNextUpdate = async ({62 timeout = DEFAULT_TIMEOUT63 }: WaitForNextUpdateOptions = {}) => {64 let updated = false65 addResolver(() => {66 updated = true67 })68 const result = await wait(() => updated, { interval: false, timeout })69 if (!result && timeout) {70 throw new TimeoutError(waitForNextUpdate, timeout)71 }72 }73 return {74 waitFor,75 waitForValueToChange,76 waitForNextUpdate77 }78}...
custom-fetch.js
Source:custom-fetch.js
1import '@ungap/global-this';2export default function customFetch(3 endpoint,4 {5 body,6 ...customConfig7 } = {},8 {9 fetch = globalThis.fetch,10 AbortController = globalThis.AbortController,11 responseType = 'text',12 timeout13 } = {},14) {15 let timeoutSignal = undefined;16 if (timeout) {17 timeoutSignal = createTimeoutSignal(AbortController, timeout);18 }19 const config = {20 method: body ? 'POST' : 'GET',21 ...customConfig22 }23 // from here: https://github.com/developit/redaxios/blob/ab73a298ba9849c59d670230a9d24fd7b329fb4d/src/index.js#L17124 if (body && typeof body === 'object' && typeof body.append !== 'function') {25 config.body = JSON.stringify(body);26 config.headers = {27 ...config.headers,28 'content-type': 'application/json'29 };30 } else if (body) {31 config.body = body;32 }33 if (timeoutSignal) {34 config.signal = timeoutSignal.signal;35 }36 return fetch(endpoint, config).then(async (response) => {37 if (timeoutSignal) {38 timeoutSignal.clear();39 }40 if (!response.ok) {41 const errorMessage = await response.text();42 return Promise.reject(new Error(errorMessage));43 }44 const result = {};45 // see https://github.com/developit/redaxios/blob/ab73a298ba9849c59d670230a9d24fd7b329fb4d/src/index.js#L204-L21346 for (const i in response) {47 if (typeof response[i] !== 'function') result[i] = response[i];48 }49 const data = await response[responseType]();50 result.data = data;51 try {52 // just in case we can parse the result53 result.data = JSON.parse(data);54 } catch(error) {55 // ignore56 }57 return result;58 });59}60function createTimeoutSignal(AbortController, timeout) {61 const controller = new AbortController();62 const timeoutId = globalThis.setTimeout(() => {63 controller.abort();64 }, timeout);65 return {66 signal: controller.signal,67 clear: () => {68 globalThis.clearTimeout(timeoutId);69 }70 };...
timeoutAbortSignal.ts
Source:timeoutAbortSignal.ts
1import { createTimeoutAbortSignal, joinAbortSignals } from "~/Util/PromiseUtils";2import { ApiRequestMiddleware, ApiRequest, ApiRequestInvoker, ApiResponse } from "../ApiInterfaces";34const timeoutAbortSignal = (defaultTimeoutMs: number): ApiRequestMiddleware => (request: ApiRequest, next: ApiRequestInvoker): Promise<ApiResponse> => {5 const timeoutMs = request.timeout || defaultTimeoutMs;6 const timeoutSignal = createTimeoutAbortSignal(timeoutMs); 7 const finalSignal = request.signal8 ? joinAbortSignals(timeoutSignal, request.signal)9 : timeoutSignal;10 return next({11 ...request,12 signal: finalSignal13 });14};
...
Using AI Code Generation
1import { act, renderHook } from '@testing-library/react-hooks'2import { useFetch } from './useFetch'3import { rest } from 'msw'4import { setupServer } from 'msw/node'5const server = setupServer(6 return res(ctx.json({ name: 'typicode' }))7 })8beforeAll(() => server.listen())9afterEach(() => server.resetHandlers())10afterAll(() => server.close())11test('should return user data', async () => {12 expect(result.current.loading).toBeTruthy()13 expect(result.current.data).toBeNull()14 await waitForNextUpdate()15 expect(result.current.loading).toBeFalsy()16 expect(result.current.data).toEqual({ name: 'typicode' })17})18test('should return error', async () => {19 server.use(20 return res(ctx.status(404))21 })22 expect(result.current.loading).toBeTruthy()23 expect(result.current.data).toBeNull()24 await waitForNextUpdate()25 expect(result.current.loading).toBeFalsy()26 expect(result.current.data).toBeNull()27 expect(result.current.error).toEqual('Not Found')28})29test('should timeout', async () => {30 server.use(31 return new Promise((resolve) => setTimeout(() => resolve(res(ctx.json({ name: 'typicode' }))), 1000))32 })33 expect(result.current.loading).toBeTruthy()34 expect(result.current.data).toBeNull()35 await waitForNextUpdate({ timeout: 500 })36 expect(result.current.loading).toBeTruthy()37 expect(result.current.data).toBeNull()38 expect(result.current.error).toEqual('Timeout')39})40test('should timeout with custom error message', async () => {41 server.use(
Using AI Code Generation
1import { timeoutSignal } from '@testing-library/react-hooks'2import { timeoutSignal } from '@testing-library/react-hooks'3import { timeoutSignal } from '@testing-library/react-hooks'4import { timeoutSignal } from '@testing-library/react-hooks'5import { timeoutSignal } from '@testing-library/react-hooks'6import { timeoutSignal } from '@testing-library/react-hooks'7import { timeoutSignal } from '@testing-library/react-hooks'8import { timeoutSignal } from '@testing-library/react-hooks'9import { timeoutSignal } from '@testing-library/react-hooks'10import { timeoutSignal } from '@testing-library/react-hooks'11import { timeoutSignal } from '@testing-library/react-hooks'12import { timeoutSignal } from '@testing-library/react-hooks'13import { timeoutSignal } from '@testing-library/react-hooks'14import { timeoutSignal } from '@testing-library/react-hooks'15import { timeoutSignal } from '@testing-library/react-hooks'16import { timeoutSignal } from '@testing-library/react-hooks'17import { timeoutSignal } from '@testing-library/react-hooks'18import { timeoutSignal } from '@testing-library/react-hooks'
Using AI Code Generation
1import { renderHook } from '@testing-library/react-hooks';2import { useFetch } from './useFetch';3test('should fetch data', async () => {4 await waitForNextUpdate();5 expect(result.current.data.title).toBe('sunt aut facere repellat provident occaecati excepturi optio reprehenderit');6});7test('should fetch data and timeout', async () => {8 await waitFor(() => result.current.error, { timeout: 1000 });9 expect(result.current.error).toBe('Request timed out');10});11test('should fetch data and timeout', async () => {12 await waitForNextUpdate({ timeout: 1000 });13 expect(result.current.error).toBe('Request timed out');14});15test('should fetch data and timeout', async () => {16 await waitForNextUpdate({ timeout: 3000 });17 expect(result.current.data.title).toBe('sunt aut facere repellat provident occaecati excepturi optio reprehenderit');18});19import { useState, useEffect } from 'react';20export const useFetch = (url, options) => {21 const [data, setData] = useState(null);22 const [error, setError] = useState(null);23 useEffect(() => {24 const controller = new AbortController();25 const { signal } = controller;26 const fetchData = async () => {27 try {28 const res = await fetch(url, { signal, ...options });29 const json = await res.json();30 setData(json);31 } catch (err) {32 setError(err);33 }34 };35 fetchData();36 return () => controller.abort();37 }, [url, options]);38 return { data, error };39};
Using AI Code Generation
1import { renderHook } from '@testing-library/react-hooks'2import useFetch from './useFetch'3const { result, waitForNextUpdate, waitForValueToChange } = renderHook(() =>4await waitForNextUpdate()5expect(result.current).toEqual(['some data', false])6await waitForValueToChange(() => result.current[1])7expect(result.current).toEqual(['some data', true])8import { useReducer } from 'react'9function useFetch(url) {10 const [state, dispatch] = useReducer(reducer, {11 })12 useEffect(() => {13 dispatch({ type: 'FETCH_INIT' })14 fetch(url)15 .then(response => response.json())16 .then(data => dispatch({ type: 'FETCH_SUCCESS', payload: data }))17 }, [url])18}19function reducer(state, action) {20 switch (action.type) {21 return { ...state, loading: true }22 return { ...state, loading: false, data: action.payload }23 throw new Error()24 }25}26import { renderHook, act } from '@testing-library/react-hooks'27import { useReducer } from 'react'28import useFetch from './useFetch'29jest.mock('react', () => ({30 ...jest.requireActual('react'),31 useReducer: jest.fn(),32}))33describe('useFetch', () => {34 test('should fetch data and update state', async () => {35 const mockFetch = jest.fn().mockImplementation(() =>36 Promise.resolve({37 json: () => Promise.resolve({ data: 'some data' }),38 })39 const mockDispatch = jest.fn()40 useReducer.mockImplementation(() => [{ data: null, loading: true }, mockDispatch])41 await waitForNextUpdate()42 expect(result.current).toEqual([{ data: 'some data', loading: false }, mockDispatch])43 })44})45import { renderHook, act } from '@testing-library/react-hooks'46import { useReducer }
Using AI Code Generation
1import { renderHook, act } from '@testing-library/react-hooks';2import { useTimeout } from './useTimeout';3test('should use timeout', async () => {4 const { result, waitForNextUpdate, timeoutSignal } = renderHook(() =>5 useTimeout(1000)6 );7 expect(result.current).toBe(false);8 await act(async () => {9 await waitForNextUpdate();10 });11 expect(result.current).toBe(true);12});13import { useState, useEffect } from 'react';14export const useTimeout = (timeout) => {15 const [isTimeout, setIsTimeout] = useState(false);16 useEffect(() => {17 const timer = setTimeout(() => {18 setIsTimeout(true);19 }, timeout);20 return () => clearTimeout(timer);21 }, [timeout]);22 return isTimeout;23};
Using AI Code Generation
1import { renderHook } from '@testing-library/react-hooks';2import { useFetch } from './useFetch';3const mockFetch = jest.fn();4mockFetch.mockResolvedValue({5 json: () => Promise.resolve({ data: 'test data' }),6});7global.fetch = mockFetch;8describe('useFetch', () => {9 it('should fetch data', async () => {10 const { result, waitForNextUpdate } = renderHook(() =>11 );12 expect(result.current.data).toBe(null);13 expect(result.current.loading).toBe(true);14 expect(result.current.error).toBe(null);15 await waitForNextUpdate();16 expect(result.current.data).toBe('test data');17 expect(result.current.loading).toBe(false);18 expect(result.current.error).toBe(null);19 });20});21import { useState, useEffect } from 'react';22export const useFetch = (url) => {23 const [data, setData] = useState(null);24 const [loading, setLoading] = useState(true);25 const [error, setError] = useState(null);26 useEffect(() => {27 fetch(url)28 .then((res) => res.json())29 .then((data) => {30 setData(data);31 setLoading(false);32 setError(null);33 })34 .catch((err) => {35 setData(null);36 setLoading(false);37 setError(err);38 });39 }, [url]);40 return { data, loading, error };41};42import { renderHook } from '@testing-library/react-hooks';43import { useFetch } from './useFetch';44const mockFetch = jest.fn();45mockFetch.mockResolvedValue({46 json: () => Promise.resolve({ data: 'test data' }),47});48global.fetch = mockFetch;49describe('useFetch', () => {50 it('should fetch data', async () => {51 const { result, waitForNextUpdate } = renderHook(() =>52 );53 expect(result.current.data).toBe(null);54 expect(result.current.loading).toBe(true);55 expect(result.current.error).toBe(null);56 await waitForNextUpdate();
Using AI Code Generation
1import { useTimeout } from './useTimeout';2import { renderHook, act } from '@testing-library/react-hooks';3describe('useTimeout', () => {4 it('should work', () => {5 const { result, waitForNextUpdate, timeoutSignal } = renderHook(() =>6 useTimeout()7 );8 expect(result.current).toBe(false);9 act(() => {10 result.current[1]();11 });12 expect(result.current).toBe(true);13 act(() => {14 timeoutSignal();15 });16 expect(result.current).toBe(false);17 });18});19import { useState } from 'react';20export const useTimeout = () => {21 const [timeout, setTimeout] = useState(false);22 let timeoutId;23 const startTimeout = () => {24 timeoutId = setTimeout(() => {25 setTimeout(false);26 }, 1000);27 };28 const cancelTimeout = () => {29 clearTimeout(timeoutId);30 setTimeout(false);31 };32 return [timeout, startTimeout, cancelTimeout];33};34export declare const useTimeout: () => [boolean, () => void, () => void];35export declare const useTimeout: () => [boolean, () => void, () => void];36export declare const useTimeout: () => [boolean, () => void, () => void];37export declare const useTimeout: () => [boolean, () => void, () => void];38export declare const useTimeout: () => [boolean, () => void, () => void];39export declare const useTimeout: () => [boolean, () => void, () => void];40export declare const useTimeout: () => [boolean, () => void, () => void];
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!