Created
July 31, 2020 05:32
-
-
Save javascripto/b5f063ac1584ab26ebb3ed861a2337ea to your computer and use it in GitHub Desktop.
Testing custom hook - SoC principle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useState } from 'react' | |
| import { render, act } from '@testing-library/react' | |
| function useCounter(init = 0) { | |
| const [state, setState] = useState(init) | |
| return { | |
| counter: state, | |
| increment: () => setState(state + 1), | |
| decrement: () => setState(state - 1), | |
| } | |
| } | |
| const Counter = () => { | |
| const { counter, increment, decrement } = useCounter(0) | |
| return ( | |
| <div> | |
| <button onClick={decrement}>Decrement</button> | |
| <button onClick={increment}>Increment</button> | |
| <div>{counter}</div> | |
| </div> | |
| ) | |
| } | |
| function renderHook<T>(useHook: () => T): ReturnType<() => T> { | |
| const returnValue = {} as T | |
| function TestComponent() { | |
| Object.assign(returnValue, useHook()) | |
| return null | |
| } | |
| render(<TestComponent/>) | |
| return returnValue | |
| } | |
| describe('Counter', () => { | |
| test('should init counter with default value 0', () => { | |
| const { counter } = renderHook(() => useCounter(undefined)) | |
| expect(counter).toBe(0) | |
| }) | |
| test('should init counter with some value', () => { | |
| const { counter } = renderHook(() => useCounter(5)) | |
| expect(counter).toBe(5) | |
| }) | |
| test('should init increment counter', () => { | |
| const hook = renderHook(() => useCounter(0)) | |
| act(() => { hook.increment() }) | |
| act(() => { hook.increment() }) | |
| expect(hook.counter).toBe(2) | |
| }) | |
| test('should init decrement counter', () => { | |
| const hook = renderHook(() => useCounter(0)) | |
| act(() => { hook.decrement() }) | |
| act(() => { hook.decrement() }) | |
| expect(hook.counter).toBe(-2) | |
| }) | |
| test('should init increment and decrement counter', () => { | |
| const hook = renderHook(() => useCounter(0)) | |
| act(() => { hook.increment() }) | |
| act(() => { hook.increment() }) | |
| act(() => { hook.decrement() }) | |
| expect(hook.counter).toBe(1) | |
| }) | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment