Best JavaScript code snippet using testing-library-react-hooks
use-stepper.test.ts
Source:use-stepper.test.ts
...152describe('useStepper', () => {153 it('should return CURRENT step', async () => {154 const {result, waitForNextUpdate} = renderHook(() => useStepper(mockSimpleSteps))155 expect(result.current.isLoading).toBe(true)156 await waitForNextUpdate() // wait for stepper to init157 expect(result.current.currentStep?.address).toEqual('1')158 })159 it('should go to NEXT step in a flat steps structure', async () => {160 const {result, waitForNextUpdate} = renderHook(() => useStepper(mockSimpleSteps))161 await waitForNextUpdate() // wait for stepper to init162 expect(result.current.currentStep?.address).toEqual('1')163 result.current.goToNextStep()164 await waitForNextUpdate()165 expect(result.current.currentStep?.address).toEqual('2')166 result.current.goToNextStep()167 await waitForNextUpdate()168 expect(result.current.currentStep?.address).toEqual('3')169 })170 it('should not break when there is no NEXT step', async () => {171 const {result, waitForNextUpdate} = renderHook(() => useStepper(mockSimpleSteps, '3'))172 await waitForNextUpdate() // wait for stepper to init173 expect(result.current.currentStep?.address).toEqual('3')174 result.current.goToNextStep()175 result.current.goToNextStep()176 expect(result.current.currentStep?.address).toEqual('3')177 })178 it('should go to NEXT step in a nested steps structure', async () => {179 const {result, waitForNextUpdate} = renderHook(() => useStepper(mockAdvancedSteps))180 await waitForNextUpdate() // wait for stepper to init181 expect(result.current.currentStep?.address).toEqual('2/2.1/2.1.1')182 result.current.goToNextStep()183 await waitForNextUpdate()184 expect(result.current.currentStep?.address).toEqual('2/2.1/2.1.3')185 result.current.goToNextStep()186 await waitForNextUpdate()187 expect(result.current.currentStep?.address).toEqual('2/2.2/2.2.1')188 result.current.goToNextStep()189 await waitForNextUpdate()190 expect(result.current.currentStep?.address).toEqual('2/2.2/2.2.2')191 result.current.goToNextStep()192 await waitForNextUpdate()193 expect(result.current.currentStep?.address).toEqual('3')194 })195 it('should go to PREV step in a flat steps structure', async () => {196 const {result, waitForNextUpdate} = renderHook(() => useStepper(mockSimpleSteps, '3'))197 await waitForNextUpdate() // wait for stepper to init198 expect(result.current.currentStep?.address).toEqual('3')199 result.current.goToPrevStep()200 await waitForNextUpdate()201 expect(result.current.currentStep?.address).toEqual('2')202 })203 it('should NOT go to PREV step if current canGoBack is false', async () => {204 const {result, waitForNextUpdate} = renderHook(() => useStepper(mockSimpleSteps, '2'))205 await waitForNextUpdate() // wait for stepper to init206 expect(result.current.currentStep.canGoBack).toBe(false)207 result.current.goToPrevStep()208 expect(result.current.currentStep?.address).toEqual('2')209 })210 it('should not break when there is no PREV step', async () => {211 const {result, waitForNextUpdate} = renderHook(() => useStepper(mockSimpleSteps, '1'))212 await waitForNextUpdate() // wait for stepper to init213 expect(result.current.currentStep?.address).toEqual('1')214 result.current.goToPrevStep()215 result.current.goToPrevStep()216 expect(result.current.currentStep?.address).toEqual('1')217 })218 it('should go to PREV step in a nested steps structure', async () => {219 const {result, waitForNextUpdate} = renderHook(() => useStepper(mockAdvancedSteps, '3'))220 await waitForNextUpdate() // wait for stepper to init221 expect(result.current.currentStep?.address).toEqual('3')222 result.current.goToPrevStep()223 await waitForNextUpdate()224 expect(result.current.currentStep?.address).toEqual('2/2.2/2.2.2')225 result.current.goToPrevStep()226 await waitForNextUpdate()227 expect(result.current.currentStep?.address).toEqual('2/2.2/2.2.1')228 result.current.goToPrevStep()229 await waitForNextUpdate()230 expect(result.current.currentStep?.address).toEqual('2/2.1/2.1.3')231 result.current.goToPrevStep()232 await waitForNextUpdate()233 expect(result.current.currentStep?.address).toEqual('2/2.1/2.1.1')234 expect(result.current.currentStep.canGoBack).toBe(false)235 })236 it('should skip steps when their shouldSkip returns true', async () => {237 const steps: Steps = {238 initialStep: '1',239 '1': {240 next: '2'241 },242 '2': {243 next: '3',244 shouldSkip: () => true245 },246 '3': {247 next: null248 }249 }250 const {result, waitForNextUpdate} = renderHook(() => useStepper(steps))251 await waitForNextUpdate() // wait for stepper to init252 expect(result.current.currentStep?.address).toEqual('1')253 result.current.goToNextStep()254 await waitForNextUpdate()255 expect(result.current.currentStep?.address).toEqual('3')256 result.current.goToPrevStep()257 await waitForNextUpdate()258 expect(result.current.currentStep?.address).toEqual('1')259 })...
useForm.test.ts
Source:useForm.test.ts
...20 );21 act(() => {22 result.current.submit();23 });24 await waitForNextUpdate({ timeout: 100 });25 expect(result.current.touches.test).toBeFalsy();26 });27 it('sets isDirty to true after submission', async () => {28 const onSubmit = jest.fn();29 const { result, waitForNextUpdate } = renderHook(() =>30 useForm({31 onSubmit,32 }),33 );34 act(() => {35 result.current.submit();36 });37 await waitForNextUpdate({ timeout: 100 });38 expect(result.current.isDirty).toBe(true);39 });40 it('will call onSubmit when the form is submitted', async () => {41 const onSubmit = jest.fn();42 const { result, waitForNextUpdate } = renderHook(() =>43 useForm({44 onSubmit,45 }),46 );47 act(() => {48 result.current.submit();49 });50 await waitForNextUpdate({ timeout: 100 });51 expect(onSubmit).toBeCalledTimes(1);52 });53 });54 describe('with non-constraint validation', () => {55 it('will not set touch on inputs', async () => {56 const onSubmit = jest.fn();57 const { result, waitForNextUpdate } = renderHook(() =>58 useForm({59 onSubmit,60 validators: {61 email: () => '',62 },63 initialValues: {64 test: 'hello',65 },66 }),67 );68 act(() => {69 result.current.submit();70 });71 await waitForNextUpdate();72 expect(result.current.touches.test).toBeFalsy();73 });74 it('sets isDirty to true after submission of an optional form', async () => {75 const onSubmit = jest.fn();76 const { result, waitForNextUpdate } = renderHook(() =>77 useForm({78 onSubmit,79 validators: {80 email: () => '',81 },82 }),83 );84 act(() => {85 result.current.submit();86 });87 await waitForNextUpdate();88 expect(result.current.isDirty).toBe(true);89 });90 it('sets isDirty to true after submission of a form', async () => {91 const onSubmit = jest.fn();92 const { result, waitForNextUpdate } = renderHook(() =>93 useForm({94 onSubmit,95 validators: {96 email: () => 'false',97 },98 }),99 );100 act(() => {101 result.current.submit();102 });103 await waitForNextUpdate();104 expect(result.current.isDirty).toBe(true);105 });106 it('will call onSubmit when the form is optional', async () => {107 const onSubmit = jest.fn();108 const { result, waitForNextUpdate } = renderHook(() =>109 useForm({110 onSubmit,111 validators: {112 email: () => '',113 },114 }),115 );116 act(() => {117 result.current.submit();118 });119 await waitForNextUpdate();120 expect(onSubmit).toBeCalledTimes(1);121 });122 it('will only call onSubmit when the form is valid', async () => {123 const onSubmit = jest.fn();124 const { result, waitForNextUpdate } = renderHook(() =>125 useForm({126 onSubmit,127 validators: {128 email: () => 'false',129 },130 }),131 );132 act(() => {133 result.current.submit();134 });135 await waitForNextUpdate();136 expect(onSubmit).toBeCalledTimes(0);137 });138 });139 describe('with constraints', () => {140 it('will not set touch on inputs', async () => {141 const onSubmit = jest.fn();142 const { result, waitForNextUpdate } = renderHook(() =>143 useForm({144 onSubmit,145 constraints: {146 email: { type: 'email', required: true },147 },148 initialValues: {149 test: 'hello',150 },151 }),152 );153 act(() => {154 result.current.submit();155 });156 await waitForNextUpdate();157 expect(result.current.touches.test).toBeFalsy();158 });159 it('sets isDirty to true after submission of an optional form', async () => {160 const onSubmit = jest.fn();161 const { result, waitForNextUpdate } = renderHook(() =>162 useForm({163 onSubmit,164 constraints: {165 email: { type: 'email', required: false },166 },167 }),168 );169 act(() => {170 result.current.submit();171 });172 await waitForNextUpdate();173 expect(result.current.isDirty).toBe(true);174 });175 it('sets isDirty to true after submission of a form', async () => {176 const onSubmit = jest.fn();177 const { result, waitForNextUpdate } = renderHook(() =>178 useForm({179 onSubmit,180 constraints: {181 email: { type: 'email', required: true },182 },183 }),184 );185 act(() => {186 result.current.submit();187 });188 await waitForNextUpdate();189 expect(result.current.isDirty).toBe(true);190 });191 it('will call onSubmit when the form is optional', async () => {192 const onSubmit = jest.fn();193 const { result, waitForNextUpdate } = renderHook(() =>194 useForm({195 onSubmit,196 constraints: {197 email: { type: 'email', required: false },198 },199 }),200 );201 act(() => {202 result.current.submit();203 });204 await waitForNextUpdate();205 expect(onSubmit).toBeCalledTimes(1);206 });207 it('will only call onSubmit when the form is valid', async () => {208 const onSubmit = jest.fn();209 const { result, waitForNextUpdate } = renderHook(() =>210 useForm({211 onSubmit,212 constraints: {213 email: { type: 'email', required: true },214 },215 }),216 );217 act(() => {218 result.current.submit();219 });220 await waitForNextUpdate();221 expect(onSubmit).toBeCalledTimes(0);222 });223 it('will not reset form inputs when submission fails', async () => {224 const onSubmit = jest.fn().mockImplementation(() => {225 return sleep(1).then(() => {226 throw 'error';227 });228 });229 const { result, waitForNextUpdate } = renderHook(() =>230 useForm({231 onSubmit,232 constraints: {233 email: { type: 'email', required: true },234 },235 }),236 );237 act(() => {238 result.current.setValue('email', 'test@example.com');239 });240 act(() => {241 result.current.submit();242 });243 await waitForNextUpdate();244 expect(onSubmit).toBeCalledTimes(1);245 expect(result.current.values.email).toEqual('test@example.com');246 });247 it('supports email types', async () => {248 const { result, waitForNextUpdate } = renderHook(() =>249 useForm({250 onSubmit() {},251 constraints: {252 email: { type: 'email' },253 },254 }),255 );256 const subtest = async (value, shouldFail?) => {257 act(() => {258 result.current.validateByName('email', value);259 });260 await waitForNextUpdate();261 let exp = expect(result.current.errors.email);262 if (shouldFail) {263 // @ts-expect-error264 exp = exp.not;265 }266 exp.toEqual(SUCCESS);267 };268 await subtest('example.com', true);269 await subtest('e@example.com');270 await subtest('john.doe@example.uk.co');271 });272 });...
useFetch.spec.js
Source:useFetch.spec.js
...23 wrapper,24 initialProps: false25 }26 );27 await waitForNextUpdate();28 rerender({ foo: 'bar', bar: 'foo' });29 await waitForNextUpdate();30 await waitForNextUpdate();31 await waitForNextUpdate();32 expect(result.current).toEqual(33 expect.objectContaining({34 isFetching: false,35 data: { foo: 'bar', bar: 'foo' }36 })37 );38 });39});40it('awaits fetching when query is a function that throws', async () => {41 await act(async () => {42 const { result, waitForNextUpdate, rerender } = renderHook(43 query => useFetch(query),44 {45 wrapper,46 initialProps: () => ({ namespace: 'wc/v2', resource: Oops })47 }48 );49 await waitForNextUpdate();50 rerender(() => ({ namespace: 'wc/v2', resource: 'products' }));51 await waitForNextUpdate();52 await waitForNextUpdate();53 await waitForNextUpdate();54 expect(result.current).toEqual(55 expect.objectContaining({56 isFetching: false,57 data: { namespace: 'wc/v2', resource: 'products' }58 })59 );60 });61});62it('calls client.query with correct params', async () => {63 await act(async () => {64 const { result, waitForNextUpdate, rerender } = renderHook(65 query => useFetch(query),66 {67 wrapper,68 initialProps: { foo: 'bar', bar: 'foo' }69 }70 );71 await waitForNextUpdate();72 await waitForNextUpdate();73 await waitForNextUpdate();74 await waitForNextUpdate();75 expect(result.current.data).toEqual({ foo: 'bar', bar: 'foo' });76 });...
Using AI Code Generation
1import { renderHook, act } from "@testing-library/react-hooks";2import { useCounter } from "./useCounter";3test("should increment counter", async () => {4 const { result, waitForNextUpdate } = renderHook(() => useCounter());5 expect(result.current.count).toBe(0);6 act(() => {7 result.current.increment();8 });9 await waitForNextUpdate();10 expect(result.current.count).toBe(1);11});12import { renderHook, act } from "@testing-library/react-hooks";13import { useCounter } from "./useCounter";14test("should increment counter", async () => {15 const { result, waitForNextUpdate } = renderHook(() => useCounter());16 expect(result.current.count).toBe(0);17 act(() => {18 result.current.increment();19 });20 await waitForNextUpdate();21 expect(result.current.count).toBe(1);22});23import { renderHook, act } from "@testing-library/react-hooks";24import { useCounter } from "./useCounter";25test("should increment counter", async () => {26 const { result, waitForNextUpdate } = renderHook(() => useCounter());27 expect(result.current.count).toBe(0);28 act(() => {29 result.current.increment();30 });31 await waitForNextUpdate();32 expect(result.current.count).toBe(1);33});34import { renderHook, act } from "@testing-library/react-hooks";35import { useCounter } from "./useCounter";36test("should increment counter", async () => {37 const { result, waitForNextUpdate } = renderHook(() => useCounter());38 expect(result.current.count).toBe(0);39 act(() => {40 result.current.increment();41 });42 await waitForNextUpdate();43 expect(result.current.count).toBe(1);44});45import { renderHook, act } from "@testing-library/react-hooks";46import { useCounter } from "./useCounter";47test("should increment counter", async () => {48 const { result, waitForNextUpdate } = renderHook(() => useCounter());49 expect(result.current
Using AI Code Generation
1import { renderHook, act } from '@testing-library/react-hooks';2import { useFetch } from './useFetch';3test('should fetch data', async () => {4 const { result, waitForNextUpdate } = renderHook(() =>5 );6 expect(result.current.loading).toBe(true);7 expect(result.current.data).toBe(null);8 await waitForNextUpdate();9 expect(result.current.loading).toBe(false);10 expect(result.current.data).toEqual({11 });12});13import { useState, useEffect } from 'react';14export const useFetch = url => {15 const [data, setData] = useState(null);16 const [loading, setLoading] = useState(true);17 useEffect(() => {18 setLoading(true);19 setTimeout(async () => {20 const response = await fetch(url);21 const data = await response.json();22 setData(data);23 setLoading(false);24 }, 1000);25 }, [url]);26 return { data, loading };27};28import React from 'react';29import './App.css';30import { useFetch } from './useFetch';31function App() {32 const { data, loading } = useFetch(33 );34 return (35 <h1>{loading ? 'loading...' : data.title}</h1>36 );37}38export default App;
Using AI Code Generation
1import { renderHook } from '@testing-library/react-hooks';2import useFetch from './useFetch';3describe('useFetch', () => {4 it('should return the data', async () => {5 const { result, waitForNextUpdate } = renderHook(() => useFetch(url));6 await waitForNextUpdate();7 expect(result.current.data.title).toBe('delectus aut autem');8 });9});10import { useState, useEffect } from 'react';11const useFetch = (url) => {12 const [data, setData] = useState(null);13 const [isPending, setIsPending] = useState(true);14 const [error, setError] = useState(null);15 useEffect(() => {16 const abortCont = new AbortController();17 fetch(url, { signal: abortCont.signal })18 .then((res) => {19 if (!res.ok) {20 throw Error('could not fetch the data for that resource');21 }22 return res.json();23 })24 .then((data) => {25 setData(data);26 setIsPending(false);27 setError(null);28 })29 .catch((err) => {30 if (err.name === 'AbortError') {31 console.log('fetch aborted');32 } else {33 setIsPending(false);34 setError(err.message);35 }36 });37 return () => abortCont.abort();38 }, [url]);39 return { data, isPending, error };40};41export default useFetch;
Using AI Code Generation
1import { renderHook, act } from "@testing-library/react-hooks";2import useFetch from "../hooks/useFetch";3import { waitForNextUpdate } from "@testing-library/react";4test("it should fetch data", async () => {5 const { result, waitForNextUpdate } = renderHook(() => useFetch());6 await waitForNextUpdate();7 expect(result.current).toEqual({ data: "hello world" });8});9import { useState, useEffect } from "react";10const useFetch = () => {11 const [data, setData] = useState(null);12 useEffect(() => {13 setData("hello world");14 }, []);15 return data;16};17export default useFetch;18import { renderHook, act } from "@testing-library/react-hooks";19import useFetch from "./useFetch";20test("it should fetch data", () => {21 const { result } = renderHook(() => useFetch());22 expect(result.current).toEqual({ data: "hello world" });23});
Using AI Code Generation
1import { renderHook, act } from '@testing-library/react-hooks';2import useFetch from './useFetch';3describe('useFetch', () => {4 it('should return data', async () => {5 await waitForNextUpdate();6 expect(result.current.data).toEqual({ userId: 1, id: 1, title: 'delectus aut autem', completed: false });7 });8});9import { useState, useEffect } from 'react';10const useFetch = (url) => {11 const [data, setData] = useState(null);12 const [loading, setLoading] = useState(true);13 const [error, setError] = useState(null);14 useEffect(() => {15 const abortCont = new AbortController();16 fetch(url, { signal: abortCont.signal })17 .then((res) => {18 if (!res.ok) {19 throw Error('could not fetch data for that resource');20 }21 return res.json();22 })23 .then((data) => {24 setData(data);25 setLoading(false);26 setError(null);27 })28 .catch((err) => {29 if (err.name === 'AbortError') {30 console.log('fetch aborted');31 } else {32 setLoading(false);33 setError(err.message);34 }35 });36 return () => abortCont.abort();37 }, [url]);38 return { data, loading, error };39};40export default useFetch;41I have a custom hook called useFetch which returns an object {data, loading, error}
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!!