or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

act-utilities.mdasync-testing.mdcleanup-management.mderror-handling.mdhook-rendering.mdindex.mdserver-side-rendering.md

index.mddocs/

0

# React Hooks Testing Library

1

2

React Hooks Testing Library provides simple and complete testing utilities for React hooks, encouraging good testing practices. It allows you to test custom hooks in isolation without creating wrapper components, handling the complexities of running hooks within function components while providing utilities for updating inputs and retrieving outputs.

3

4

## Package Information

5

6

- **Package Name**: @testing-library/react-hooks

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install --save-dev @testing-library/react-hooks`

10

11

## Core Imports

12

13

```typescript

14

import { renderHook, act } from "@testing-library/react-hooks";

15

```

16

17

For specific renderer environments:

18

19

```typescript

20

// DOM environment (default auto-detected)

21

import { renderHook, act } from "@testing-library/react-hooks/dom";

22

23

// React Native environment

24

import { renderHook, act } from "@testing-library/react-hooks/native";

25

26

// Server-side rendering environment

27

import { renderHook, act } from "@testing-library/react-hooks/server";

28

29

// Pure environment (no auto-setup)

30

import { renderHook, act } from "@testing-library/react-hooks/pure";

31

```

32

33

CommonJS:

34

35

```javascript

36

const { renderHook, act } = require("@testing-library/react-hooks");

37

```

38

39

## Basic Usage

40

41

```typescript

42

import { renderHook, act } from "@testing-library/react-hooks";

43

import { useState } from "react";

44

45

// Test a simple custom hook

46

function useCounter(initialCount = 0) {

47

const [count, setCount] = useState(initialCount);

48

49

const increment = () => setCount(prev => prev + 1);

50

const decrement = () => setCount(prev => prev - 1);

51

52

return { count, increment, decrement };

53

}

54

55

test("useCounter hook", () => {

56

const { result } = renderHook(() => useCounter(5));

57

58

// Check initial value

59

expect(result.current.count).toBe(5);

60

61

// Test increment

62

act(() => {

63

result.current.increment();

64

});

65

66

expect(result.current.count).toBe(6);

67

68

// Test decrement

69

act(() => {

70

result.current.decrement();

71

});

72

73

expect(result.current.count).toBe(5);

74

});

75

```

76

77

## Architecture

78

79

React Hooks Testing Library is built around several key components:

80

81

- **renderHook Function**: Core testing utility that renders hooks in a test environment

82

- **act Utility**: Wraps state updates to ensure proper batching and timing

83

- **Renderer Abstraction**: Supports multiple React renderers (DOM, Native, Server)

84

- **Async Utilities**: Built-in utilities for waiting on asynchronous hook updates

85

- **Cleanup System**: Automatic and manual cleanup of rendered hooks

86

- **Error Handling**: Comprehensive error boundary and suppression utilities

87

88

## Capabilities

89

90

### Hook Rendering

91

92

Core functionality for rendering and testing React hooks in isolation. The `renderHook` function creates a test harness that runs your hook within a proper React component context.

93

94

```typescript { .api }

95

function renderHook<TProps, TResult>(

96

callback: (props: TProps) => TResult,

97

options?: RenderHookOptions<TProps>

98

): RenderHookResult<TProps, TResult>;

99

100

interface RenderHookOptions<TProps> {

101

initialProps?: TProps;

102

wrapper?: React.ComponentType<TProps>;

103

}

104

```

105

106

[Hook Rendering](./hook-rendering.md)

107

108

### Act Utilities

109

110

State update wrapping utilities that ensure proper timing and batching of React updates during testing. Essential for testing hooks that perform state updates or side effects.

111

112

```typescript { .api }

113

function act(callback: () => void | undefined): void;

114

function act(callback: () => Promise<void | undefined>): Promise<undefined>;

115

```

116

117

[Act Utilities](./act-utilities.md)

118

119

### Async Testing

120

121

Utilities for testing asynchronous hook behavior, including waiting for updates, value changes, and condition fulfillment.

122

123

```typescript { .api }

124

interface AsyncUtils {

125

waitFor(callback: () => boolean | void, options?: WaitForOptions): Promise<void>;

126

waitForValueToChange(selector: () => unknown, options?: WaitForValueToChangeOptions): Promise<void>;

127

waitForNextUpdate(options?: WaitForNextUpdateOptions): Promise<void>;

128

}

129

130

interface WaitForOptions {

131

interval?: number | false;

132

timeout?: number | false;

133

}

134

```

135

136

[Async Testing](./async-testing.md)

137

138

### Cleanup Management

139

140

Cleanup utilities for managing test teardown, both automatic and manual cleanup of rendered hooks and associated resources.

141

142

```typescript { .api }

143

function cleanup(): Promise<void>;

144

function addCleanup(callback: CleanupCallback): () => void;

145

function removeCleanup(callback: CleanupCallback): void;

146

147

type CleanupCallback = () => Promise<void> | void;

148

```

149

150

[Cleanup Management](./cleanup-management.md)

151

152

### Error Handling

153

154

Error suppression and handling utilities for testing error scenarios and managing console output during tests.

155

156

```typescript { .api }

157

function suppressErrorOutput(): () => void;

158

```

159

160

[Error Handling](./error-handling.md)

161

162

### Server-Side Rendering

163

164

Server-specific rendering capabilities for testing hooks in SSR environments with hydration support. Only available when using the server renderer.

165

166

```typescript { .api }

167

interface ServerRenderHookResult<TProps, TValue> extends RenderHookResult<TProps, TValue> {

168

hydrate(): void;

169

}

170

```

171

172

When using `@testing-library/react-hooks/server`, the `renderHook` function returns a result that includes a `hydrate()` method for testing server-side rendering scenarios.

173

174

[Server-Side Rendering](./server-side-rendering.md)

175

176

## Types

177

178

```typescript { .api }

179

interface RenderHookResult<TProps, TValue> {

180

result: {

181

readonly current: TValue;

182

readonly all: Array<TValue | Error>;

183

readonly error?: Error;

184

};

185

rerender: (newProps?: TProps) => void;

186

unmount: () => void;

187

waitFor: (callback: () => boolean | void, options?: WaitForOptions) => Promise<void>;

188

waitForValueToChange: (selector: () => unknown, options?: WaitForValueToChangeOptions) => Promise<void>;

189

waitForNextUpdate: (options?: WaitForNextUpdateOptions) => Promise<void>;

190

}

191

192

interface WrapperComponent<TProps> extends React.ComponentType<TProps> {}

193

194

type Act = {

195

(callback: () => Promise<void | undefined>): Promise<undefined>;

196

(callback: () => void | undefined): void;

197

}

198

199

interface WaitForOptions {

200

interval?: number | false;

201

timeout?: number | false;

202

}

203

204

interface WaitForValueToChangeOptions {

205

interval?: number | false;

206

timeout?: number | false;

207

}

208

209

interface WaitForNextUpdateOptions {

210

timeout?: number | false;

211

}

212

213

class TimeoutError extends Error {

214

constructor(util: Function, timeout: number);

215

}

216

```