Best JavaScript code snippet using testing-library-react-hooks
useMetamask.test.js
Source:useMetamask.test.js
...50 modifyListener();51 });52 afterAll(() => cleanup())53 test("isConnected should be false", () => {54 const { result } = renderHook(() => useMetamask(), { wrapper });55 expect(result.current.metaState.isConnected).toBe(false);56 });57 test("should connect", async () => {58 const { result } = renderHook(() => useMetamask(), { wrapper });59 await act(async () => {60 await result.current.connect(Web3Interface);61 });62 expect(result.current.metaState.isConnected).toBe(true);63 });64 test("should return address", async () => {65 const { result } = renderHook(() => useMetamask(), { wrapper });66 await act(async () => {67 await result.current.connect(Web3Interface);68 });69 expect(result.current.metaState.account).toContain("0xSomething");70 });71 test("should return chainId", async () => {72 const { result } = renderHook(() => useMetamask(), { wrapper });73 await act(async () => {74 await result.current.connect(Web3Interface);75 });76 expect(result.current.metaState.chain.id).toBe("1");77 });78 test("should return local chainId", async () => {79 modifyListener(1000000000);80 const { result } = renderHook(() => useMetamask(), { wrapper });81 await act(async () => {82 await result.current.connect(Web3Interface);83 });84 expect(result.current.metaState.chain.id).toBe("1000000000");85 });86 test("should return ropsten chainName", async () => {87 modifyListener(3);88 const { result } = renderHook(() => useMetamask(), { wrapper });89 await act(async () => {90 await result.current.connect(Web3Interface);91 });92 expect(result.current.metaState.chain.name).toBe("ropsten");93 });94 test("should return rinkeby chainName", async () => {95 modifyListener(4);96 const { result } = renderHook(() => useMetamask(), { wrapper });97 await act(async () => {98 await result.current.connect(Web3Interface);99 });100 expect(result.current.metaState.chain.name).toBe("rinkeby");101 });102 test("should return goerli chainName", async () => {103 modifyListener(5);104 const { result } = renderHook(() => useMetamask(), { wrapper });105 await act(async () => {106 await result.current.connect(Web3Interface);107 });108 expect(result.current.metaState.chain.name).toBe("goerli");109 });110 test("should return kovan chainName", async () => {111 modifyListener(42);112 const { result } = renderHook(() => useMetamask(), { wrapper });113 await act(async () => {114 await result.current.connect(Web3Interface);115 });116 expect(result.current.metaState.chain.name).toBe("kovan");117 });118 test("should return unknown chainName", async () => {119 modifyListener(999);120 const { result } = renderHook(() => useMetamask(), { wrapper });121 await act(async () => {122 await result.current.connect(Web3Interface);123 });124 expect(result.current.metaState.chain.name).toBe("unknown");125 });126 test("should not change any state, if action type is unknown", async () => {127 const { result } = renderHook(() => useMetamask(), { wrapper });128 await act(async () => {129 await result.current.connect(Web3Interface);130 });131 expect(result.current.metaState.chain.id).toBe("1");132 });133 test("should throw error on getNetwork", async () => {134 modifyRequest(Error("unexpected error"));135 const { result } = renderHook(() => useMetamask(), { wrapper });136 await act(async () => {137 try {138 await result.current.connect(Web3Interface);139 } catch (error) {140 expect(error.message).toEqual("Error: unexpected error");141 }142 });143 });144 test("should throw error on getAccount", async () => {145 modifyRequest(1, Error("unexpected error"));146 const { result } = renderHook(() => useMetamask(), { wrapper });147 await act(async () => {148 try {149 await result.current.connect(Web3Interface);150 } catch (error) {151 expect(error.message).toEqual("Error: unexpected error");152 }153 });154 });155 test("should throw error for missing Web3Interface", async () => {156 const { result } = renderHook(() => useMetamask(), { wrapper });157 await act(async () => {158 try {159 await result.current.connect();160 } catch (error) {161 expect(error.message).toEqual(162 "Web3 Provider is required. You can use either ethers.js or web3.js."163 );164 }165 });166 });167 test("should be able to accept web3Interface options", async () => {168 const { result } = renderHook(() => useMetamask(), { wrapper });169 await act(async () => {170 await result.current.connect(Web3Interface, { test: "" });171 expect(result.current.metaState.isConnected).toBe(true);172 });173 });174 test("should not connect if there is no account available", async () => {175 modifyRequest(1, []);176 modifyListener(1, []);177 const { result } = renderHook(() => useMetamask(), { wrapper });178 await act(async () => {179 await result.current.connect(Web3Interface);180 expect(result.current.metaState.isConnected).toBe(false);181 });182 });183 test("should change connect status if account disconnected", async () => {184 modifyRequest(1, ["0xSomething"]);185 modifyListener(1, []);186 const { result } = renderHook(() => useMetamask(), { wrapper });187 await act(async () => {188 await result.current.connect(Web3Interface);189 expect(result.current.metaState.isConnected).toBe(false);190 });191 });192 test("should raise warning if given action is null/undefined", async () => {193 // store.js194 Object.defineProperty(typeStateMap, "SET_ACCOUNT", {195 get: jest.fn(() => null),196 });197 const { result } = renderHook(() => useMetamask(), { wrapper });198 await act(async () => {199 await result.current.connect(Web3Interface);200 expect(result.current.metaState.isConnected).toBe(true);201 });202 });203 test("should raise error if connect method re-called before the one resolved", async () => {204 const { result } = renderHook(() => useMetamask(), { wrapper });205 await act(async () => {206 try {207 result.current.connect(Web3Interface);208 await result.current.connect(Web3Interface);209 } catch (error) {210 expect(error.message).toEqual("Connect method already called.");211 }212 });213 });214 test("should raise an error if component unmounted earlier", async () => {215 jest.spyOn(React, "useRef").mockReturnValue({216 current: false,217 });218 const { result } = renderHook(() => useMetamask(), { wrapper });219 await act(async () => {220 try {221 await result.current.connect(Web3Interface);222 } catch (error) {223 expect(error.message).toEqual("Component is not mounted.");224 }225 });226 });227 test("getAccounts should call the account without Metamask permission", async () => {228 const { result } = renderHook(() => useMetamask(), { wrapper });229 await act(async () => {230 await result.current.getAccounts();231 expect(result.current.metaState.isConnected).toBe(true);232 expect(result.current.metaState.account).toEqual(["0xSomethingWithoutPermission"]);233 });234 });235 test("getChain should return current chain information", async () => {236 const { result } = renderHook(() => useMetamask(), { wrapper });237 await act(async () => {238 await result.current.getChain();239 expect(result.current.metaState.chain).toEqual({id: "1", name: "mainnet"});240 });241 });242});243describe("When Metamask is not Available", () => {244 const Web3Interface = jest.fn();245 let wrapper;246 247 beforeAll(() => {248 jest.spyOn(console, "warn").mockImplementation(() => {});249 window.ethereum = undefined;250 wrapper = ({ children }) => (251 <MetamaskStateProvider>{children}</MetamaskStateProvider>252 );253 });254 test("isAvailable should be false", () => {255 const { result } = renderHook(() => useMetamask(), { wrapper });256 expect(result.current.metaState.isAvailable).toBe(false);257 });258 test("should raise error when connect", async () => {259 const { result } = renderHook(() => useMetamask(), { wrapper });260 await act(async () => {261 try {262 await result.current.connect(Web3Interface);263 } catch (error) {264 expect(error.message).toEqual("Metamask is not available.");265 }266 });267 });268 test("getAccounts should return with a warning", async () => {269 const { result } = renderHook(() => useMetamask(), { wrapper });270 await act(async () => {271 await result.current.getAccounts();272 expect(result.current.metaState.account).toEqual([]);273 });274 });275 test("getChain should return empty chain information", async () => {276 const { result } = renderHook(() => useMetamask(), { wrapper });277 await act(async () => {278 await result.current.getChain();279 expect(result.current.metaState.chain).toEqual({id: null, name: ""});280 });281 });...
useForm.spec.js
Source:useForm.spec.js
...5 it('should be a function', () => {6 expect(typeof useForm).toBe('function');7 });8 it('should require the `validations` option', () => {9 renderHook(() => {10 expect(() => {11 useForm({});12 }).toThrow('the option `validations` is required');13 });14 });15 it('should require the validation option to be an object', () => {16 renderHook(() => {17 expect(() => {18 useForm({19 validations: true,20 });21 }).toThrow('the option `validations` should be an object');22 });23 });24 });25 describe('validateField', () => {26 describe('required', () => {27 it("should return a default error message for fields that don't have a value", () => {28 const { result } = renderHook(() => useForm({29 validations: {30 name: {31 required: true,32 },33 },34 }));35 expect(result.current.validateField('name', '')).toBe('required');36 });37 it('should return a custom error message', () => {38 const { result } = renderHook(() => useForm({39 validations: {40 name: {41 required: 'the field "name" is required',42 },43 },44 }));45 expect(result.current.validateField('name', '')).toBe('the field "name" is required');46 });47 });48 describe('pattern', () => {49 it('should return an error message if the value does not satisfy the pattern', () => {50 const { result } = renderHook(() => useForm({51 validations: {52 email: {53 pattern: {54 value: /\w+@\w+\.com/gi,55 },56 },57 },58 }));59 expect(result.current.validateField('email', '')).toBe('invalid');60 });61 it('should return an custom error message if the message attribute exists', () => {62 const { result } = renderHook(() => useForm({63 validations: {64 email: {65 pattern: {66 value: /\w+@\w+\.com/gi,67 message: 'Invalid e-mail',68 },69 },70 },71 }));72 expect(result.current.validateField('email', '')).toBe('Invalid e-mail');73 });74 });75 describe('validate', () => {76 let validateMock;77 let hook;78 beforeEach(() => {79 validateMock = jest.fn((value) => {80 if (Number(value) < 18) {81 return 'You are not able to get a drive permission';82 }83 return '';84 });85 const { result } = renderHook(() => useForm({86 validations: {87 age: {88 validate: validateMock,89 },90 },91 }));92 hook = result.current;93 });94 it('should execute the validate function passing the field value', () => {95 hook.validateField('age', '10');96 expect(validateMock).toHaveBeenCalledWith('10');97 });98 it('should be executed and return a string', () => {99 hook.validateField('age', '10');100 expect(validateMock).toHaveBeenCalled();101 expect(typeof validateMock.mock.results[0].value).toBe('string');102 });103 it('should return an error message', () => {104 hook.validateField('age', '10');105 expect(validateMock.mock.results[0].value).toBe('You are not able to get a drive permission');106 });107 it('should return an empty string when value is valid', () => {108 hook.validateField('age', '20');109 expect(validateMock.mock.results[0].value).toBe('');110 });111 });112 });113 describe('bindField', () => {114 it('should validate the name parameter', () => {115 const { result } = renderHook(() => useForm({116 validations: {117 name: {118 required: true,119 }120 }121 }));122 expect(() => {123 result.current.bindField();124 }).toThrow('The field name parameter is required');125 expect(() => {126 result.current.bindField(1);127 }).toThrow('The field name should be a string');128 });129 it('should return an object with value and onChange attributes', () => {130 const { result } = renderHook(() => useForm({131 validations: {132 name: {133 required: true,134 }135 }136 }));137 expect(result.current.bindField('name')).toEqual({138 value: expect.any(String),139 onChange: expect.any(Function),140 });141 });142 describe('onChange', () => {143 it('should update the Hook state when called', () => {144 const { result } = renderHook(() => useForm({145 validations: {146 name: {147 required: true,148 },149 },150 }));151 const bindFieldResult = result.current.bindField('name');152 act(() => {153 bindFieldResult.onChange({ target: { value: 'John' } });154 });155 expect(result.current.values.name).toBe('John');156 expect(result.current.errors.name).toBe('');157 act(() => {158 bindFieldResult.onChange({ target: { value: '' } });159 });160 expect(result.current.values.name).toBe('');161 expect(result.current.errors.name).toBe('required');162 });163 });164 });165 describe('initialValues', () => {166 it('should trhow an Error if the initialValues is not an object', () => {167 renderHook(() => {168 expect(() => {169 useForm({170 initialValues: true,171 })172 }).toThrow('the option `initialValues` should be an object');173 });174 });175 it('should initialize the values state with the initial values', () => {176 const { result } = renderHook(() => useForm({177 initialValues: {178 name: 'Carlos',179 },180 validations: {},181 }));182 expect(result.current.values.name).toBe('Carlos');183 });184 });185 describe('isValid', () => {186 it('should be a function', () => {187 const { result } = renderHook(() => useForm({188 validations: {},189 }));190 expect(typeof result.current.isValid).toBe('function');191 });192 it('should return false when it finds any error on the form', () => {193 const { result } = renderHook(() => useForm({194 initialValues: {195 name: 'Carlos',196 surname: '',197 },198 validations: {199 name: {200 required: true,201 },202 surname: {203 required: true,204 },205 birthDate: {206 pattern: {207 value: /^\d{2}\/\d{2}\/\d{4}$/gi,208 message: 'invalid date',209 },210 },211 },212 }));213 expect(result.current.isValid()).toBe(false);214 });215 it('should return true if all the form fields are valid', () => {216 const { result } = renderHook(() => useForm({217 initialValues: {218 name: 'Carlos',219 surname: 'Silva',220 birthDate: '28/10/1990',221 },222 validations: {223 name: {224 required: true,225 },226 surname: {227 required: true,228 },229 birthDate: {230 pattern: {...
index.test.js
Source:index.test.js
...8import {renderHook, act} from '@testing-library/react-hooks';9import usePagination, {NO_TOTAL_PAGES_ERROR} from './index';10describe('UsePagination hook', () => {11 it('should exist', () => {12 const {result} = renderHook(() => usePagination({totalPages: 10}));13 expect(result.current).toBeDefined();14 });15 it('should throw if no total pages were given to it', () => {16 expect(() => {17 usePagination();18 }).toThrow(NO_TOTAL_PAGES_ERROR);19 });20 it('should return the totalPages that was given to it', () => {21 const mockTotalPages = 10;22 const {result} = renderHook(() => usePagination({totalPages: mockTotalPages}));23 expect(result.current.totalPages).toEqual(mockTotalPages);24 });25 it('should return 0 as the cursor position if no cursor was given to it', () => {26 const {result} = renderHook(() => usePagination({totalPages: 10}));27 expect(result.current.cursor).toEqual(0);28 });29 it('should return the received cursor position if it was given to it', () => {30 const {result} = renderHook(() => usePagination({totalPages: 10, initialCursor: 5}));31 expect(result.current.cursor).toEqual(5);32 });33 it('should return the hooks methods', () => {34 const {result} = renderHook(() => usePagination({totalPages: 10}));35 expect(typeof result.current.goNext).toEqual('function');36 expect(typeof result.current.goPrev).toEqual('function');37 expect(typeof result.current.setCursor).toEqual('function');38 });39 describe('setCursor method', () => {40 it('should set the hooks cursor to the given value', () => {41 const {result} = renderHook(() => usePagination({totalPages: 10}));42 act(() => {43 result.current.setCursor(4);44 });45 expect(result.current.cursor).toEqual(4);46 });47 it('should not set the hooks cursor if the given value is above the total pages', () => {48 const {result} = renderHook(() => usePagination({totalPages: 10}));49 act(() => {50 result.current.setCursor(15);51 });52 expect(result.current.cursor).toEqual(0);53 });54 it('should not set the hooks cursor if the given value is lower than 0', () => {55 const {result} = renderHook(() => usePagination({totalPages: 10}));56 act(() => {57 result.current.setCursor(-3);58 });59 expect(result.current.cursor).toEqual(0);60 });61 });62 describe('goNext method', () => {63 it('should set the hooks cursor to the next value', () => {64 const {result} = renderHook(() => usePagination({totalPages: 2}));65 act(() => {66 result.current.goNext();67 });68 expect(result.current.cursor).toEqual(1);69 });70 it('should not set the hooks cursor to the next value if we reached the last page', () => {71 const {result} = renderHook(() => usePagination({totalPages: 5, initialCursor: 4}));72 act(() => {73 result.current.goNext();74 });75 expect(result.current.cursor).toEqual(4);76 });77 });78 describe('goPrev method', () => {79 it('should set the hooks cursor to the prev value', () => {80 const {result} = renderHook(() => usePagination({totalPages: 5, initialCursor: 4}));81 act(() => {82 result.current.goPrev();83 });84 expect(result.current.cursor).toEqual(3);85 });86 it('should not set the hooks cursor to the prev value if we reached the first page', () => {87 const {result} = renderHook(() => usePagination({totalPages: 5}));88 act(() => {89 result.current.goPrev();90 });91 expect(result.current.cursor).toEqual(0);92 });93 });94 describe('onChange callback handler', () => {95 it('should be invoked when the cursor changes by setCursor method', () => {96 const onChangeSpy = jest.fn();97 const {result} = renderHook(() => usePagination({totalPages: 5, onChange: onChangeSpy}));98 act(() => {99 result.current.setCursor(3);100 });101 expect(onChangeSpy).toHaveBeenCalledWith(3);102 });103 it('should not be invoked when the hook is initialized', () => {104 const onChangeSpy = jest.fn();105 renderHook(() => usePagination({totalPages: 5, onChange: onChangeSpy}));106 expect(onChangeSpy).not.toHaveBeenCalled();107 });108 });...
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).toHaveLength(10);6});7import { useState, useEffect } from 'react';8import axios from 'axios';9export const useFetch = (url) => {10 const [data, setData] = useState(null);11 useEffect(() => {12 const fetchData = async () => {13 const response = await axios(url);14 setData(response.data);15 };16 fetchData();17 }, [url]);18 return { data };19};
Using AI Code Generation
1import { renderHook, act } from '@testing-library/react-hooks';2import { useCounter } from '../useCounter';3describe('useCounter', () => {4 it('should increment the counter by 1', () => {5 const { result } = renderHook(() => useCounter());6 act(() => {7 result.current.increment();8 });9 expect(result.current.count).toBe(1);10 });11});12import { useState } from 'react';13export const useCounter = () => {14 const [count, setCount] = useState(0);15 const increment = () => {16 setCount(count + 1);17 };18 return { count, increment };19};
Using AI Code Generation
1import { renderHook } from '@testing-library/react-hooks'2import { useCounter } from './useCounter'3describe('useCounter', () => {4 it('should use the counter', () => {5 const { result } = renderHook(() => useCounter())6 expect(result.current.count).toBe(0)7 act(() => {8 result.current.increment()9 })10 expect(result.current.count).toBe(1)11 })12})13export const useCounter = () => {14 const [count, setCount] = useState(0)15 const increment = () => setCount(count + 1)16 return { count, increment }17}18import { useCounter } from './useCounter'19import { renderHook, act } from '@testing-library/react-hooks'20describe('useCounter', () => {21 it('should use the counter', () => {22 const { result } = renderHook(() => useCounter())23 expect(result.current.count).toBe(0)24 act(() => {25 result.current.increment()26 })27 expect(result.current.count).toBe(1)28 })29})30export const useCounter = () => {31 const [count, setCount] = useState(0)32 const increment = () => setCount(count + 1)33 return { count, increment }34}35import { useCounter } from './useCounter'36import { renderHook, act } from '@testing-library/react-hooks'37describe('useCounter', () => {38 it('should use the counter', () => {39 const { result } = renderHook(() => useCounter())40 expect(result.current.count).toBe(0)41 act(() => {42 result.current.increment()43 })44 expect(result.current.count).toBe(1)45 })46})47export const useCounter = () => {48 const [count, setCount] = useState(0)49 const increment = () => setCount(count + 1)50 return { count, increment }51}52import { useCounter } from './useCounter'53import { renderHook, act } from '@testing-library/react-hooks'54describe('useCounter', () => {55 it('should use the counter', () => {56 const { result } = renderHook(() => useCounter())
Using AI Code Generation
1import { renderHook } from '@testing-library/react-hooks';2import { useFetch } from './useFetch';3describe('useFetch', () => {4 it('should return the initial value', () => {5 expect(result.current).toEqual({6 });7 });8});9import { useState, useEffect } from 'react';10export const useFetch = (url) => {11 const [state, setState] = useState({12 });13 useEffect(() => {14 setState({15 });16 fetch(url)17 .then((x) => x.text())18 .then((y) => {19 setState({20 });21 });22 }, [url, setState]);23 return state;24};25import React from 'react';26import { useFetch } from './useFetch';27function App() {28 return (29 {loading ? 'loading...' : data}30 {error ? error : null}31 );32}33export default App;34const express = require('express');35const app = express();36const port = 3001;37app.get('/', (req, res) => {38 res.send('Hello World!');39});40app.listen(port, () => {41});42{43 "dependencies": {
Using AI Code Generation
1import { renderHook, act } from '@testing-library/react-hooks';2import { useCounter } from './useCounter';3test('useCounter', () => {4 const { result } = renderHook(() => useCounter(0));5 expect(result.current.count).toBe(0);6 act(() => {7 result.current.increment();8 });9 expect(result.current.count).toBe(1);10 act(() => {11 result.current.decrement();12 });13 expect(result.current.count).toBe(0);14});15import { useState } from 'react';16export const useCounter = (initialCount) => {17 const [count, setCount] = useState(initialCount);18 const increment = () => {19 setCount(count + 1);20 };21 const decrement = () => {22 setCount(count - 1);23 };24 return { count, increment, decrement };25};26import { renderHook, act } from '@testing-library/react-hooks';27import { useCounter } from './useCounter';28test('useCounter', () => {29 const { result } = renderHook(() => useCounter(0));30 expect(result.current.count).toBe(0);31 act(() => {32 result.current.increment();33 });34 expect(result.current.count).toBe(1);35 act(() => {36 result.current.decrement();37 });38 expect(result.current.count).toBe(0);39});40import { useState } from 'react';41export const useCounter = (initialCount) => {42 const [count, setCount] = useState(initialCount);43 const increment = () => {44 setCount(count + 1);45 };46 const decrement = () => {47 setCount(count - 1);48 };49 return { count, increment, decrement };50};51import { renderHook, act } from '@testing-library/react-hooks';52import { useCounter } from './useCounter';53test('useCounter', () => {54 const { result } = renderHook(() => useCounter(0));55 expect(result.current.count).toBe(0);56 act(() => {57 result.current.increment();58 });59 expect(result.current.count
Using AI Code Generation
1import { renderHook, act } from '@testing-library/react-hooks' 2import { useCounter } from './useCounter'3it('should increment the counter', () => {4 const { result } = renderHook(() => useCounter())5 act(() => {6 result.current.increment()7 })8 expect(result.current.count).toBe(1)9})10import { useState } from 'react'11export const useCounter = () => {12 const [count, setCount] = useState(0)13 const increment = () => setCount(count + 1)14 return {15 }16}
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!!