or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-jest-mock-extended

Type safe mocking extensions for jest

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/jest-mock-extended@4.0.x

To install, run

npx @tessl/cli install tessl/npm-jest-mock-extended@4.0.0

0

# Jest Mock Extended

1

2

Jest Mock Extended provides comprehensive type-safe mocking extensions for the Jest testing framework. It enables developers to create fully typed mock objects for interfaces and classes with complete TypeScript type safety, offering advanced mocking capabilities including argument-specific expectations, deep object mocking, and extensive matcher API.

3

4

## Package Information

5

6

- **Package Name**: jest-mock-extended

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install jest-mock-extended --save-dev`

10

11

## Core Imports

12

13

```typescript

14

import {

15

mock,

16

mockDeep,

17

MockProxy,

18

DeepMockProxy,

19

DeepMockProxyWithFuncPropSupport,

20

any,

21

anyString,

22

anyNumber

23

} from "jest-mock-extended";

24

```

25

26

For CommonJS:

27

28

```javascript

29

const { mock, mockDeep, any, anyString, anyNumber } = require("jest-mock-extended");

30

```

31

32

## Basic Usage

33

34

```typescript

35

import { mock, MockProxy } from "jest-mock-extended";

36

37

interface UserService {

38

getUser: (id: string) => Promise<User>;

39

deleteUser: (id: string) => void;

40

}

41

42

// Create a type-safe mock

43

const userService: MockProxy<UserService> = mock<UserService>();

44

45

// Set up expectations with argument matching

46

userService.getUser.calledWith("123").mockResolvedValue({ id: "123", name: "John" });

47

48

// Use in tests

49

test("should get user", async () => {

50

const result = await userService.getUser("123");

51

expect(result).toEqual({ id: "123", name: "John" });

52

expect(userService.getUser).toHaveBeenCalledWith("123");

53

});

54

```

55

56

## Architecture

57

58

Jest Mock Extended is built around several key components:

59

60

- **Mock Proxy System**: Creates type-safe proxies that preserve TypeScript type information while adding Jest mock functionality

61

- **Argument Matching**: `calledWith()` extension for creating expectations based on specific argument patterns

62

- **Deep Mocking**: Recursive mocking system for nested objects and complex data structures

63

- **Matcher System**: Extensive built-in matchers with support for custom matcher creation

64

- **Global Configuration**: Centralized configuration system for controlling mock behavior across your test suite

65

66

## Capabilities

67

68

### Basic Mocking

69

70

Core mock creation functionality for interfaces and classes with full TypeScript type safety and Jest integration.

71

72

```typescript { .api }

73

function mock<T>(

74

mockImplementation?: DeepPartial<T>,

75

opts?: MockOpts

76

): MockProxy<T> & T;

77

78

interface MockProxy<T> {

79

[K in keyof T]: T[K] extends FunctionLike

80

? T[K] & CalledWithMock<T[K]>

81

: T[K];

82

}

83

84

interface MockOpts {

85

deep?: boolean;

86

fallbackMockImplementation?: (...args: any[]) => any;

87

}

88

```

89

90

[Basic Mocking](./basic-mocking.md)

91

92

### Deep Mocking

93

94

Advanced mocking capabilities for nested objects and complex data structures with recursive type-safe mocking.

95

96

```typescript { .api }

97

function mockDeep<T>(

98

opts: {

99

funcPropSupport?: true;

100

fallbackMockImplementation?: MockOpts['fallbackMockImplementation']

101

},

102

mockImplementation?: DeepPartial<T>

103

): DeepMockProxyWithFuncPropSupport<T>;

104

105

function mockDeep<T>(mockImplementation?: DeepPartial<T>): DeepMockProxy<T>;

106

107

type DeepMockProxy<T> = _DeepMockProxy<T> & T;

108

```

109

110

[Deep Mocking](./deep-mocking.md)

111

112

### Argument Matching

113

114

Sophisticated argument matching system with calledWith() extension for creating expectations based on specific argument patterns.

115

116

```typescript { .api }

117

interface CalledWithMock<T extends FunctionLike> extends jest.Mock<T> {

118

calledWith: (...args: [...MatchersOrLiterals<Parameters<T>>]) => jest.Mock<T>;

119

}

120

121

function mockFn<T extends FunctionLike>(): CalledWithMock<T> & T;

122

123

function calledWithFn<T extends FunctionLike>(

124

options?: { fallbackMockImplementation?: T }

125

): CalledWithMock<T>;

126

```

127

128

[Argument Matching](./argument-matching.md)

129

130

### Matchers

131

132

Extensive built-in matcher system with type-safe argument validation and support for custom matcher creation.

133

134

```typescript { .api }

135

class Matcher<T> implements MatcherLike<T> {

136

constructor(asymmetricMatch: MatcherFn<T>, description: string);

137

asymmetricMatch(other: unknown): boolean;

138

toString(): string;

139

}

140

141

// Built-in matchers

142

function any<T>(): Matcher<T>;

143

function anyString(): Matcher<string>;

144

function anyNumber(): Matcher<number>;

145

function anyBoolean(): Matcher<boolean>;

146

```

147

148

[Matchers](./matchers.md)

149

150

### Utilities

151

152

Mock management utilities for clearing, resetting, and configuring mock behavior globally.

153

154

```typescript { .api }

155

function mockClear(mock: MockProxy<any>): void;

156

function mockReset(mock: MockProxy<any>): void;

157

function stub<T extends object>(): T;

158

159

interface GlobalConfig {

160

ignoreProps?: ProxiedProperty[];

161

}

162

163

const JestMockExtended: {

164

DEFAULT_CONFIG: GlobalConfig;

165

configure: (config: GlobalConfig) => void;

166

resetConfig: () => void;

167

};

168

```

169

170

[Utilities](./utilities.md)

171

172

## Types

173

174

```typescript { .api }

175

interface MockOpts {

176

/** Enable deep mocking for nested objects */

177

deep?: boolean;

178

/** Fallback implementation when no expectation is set */

179

fallbackMockImplementation?: (...args: any[]) => any;

180

}

181

182

interface CalledWithMock<T extends FunctionLike> extends jest.Mock<T> {

183

calledWith: (...args: [...MatchersOrLiterals<Parameters<T>>]) => jest.Mock<T>;

184

}

185

186

type MatchersOrLiterals<Y extends any[]> = {

187

[K in keyof Y]: MatcherLike<Y[K]> | Y[K]

188

};

189

190

type MatcherFn<T> = (actualValue: T) => boolean;

191

192

interface MatcherCreator<T, E = T> {

193

(expectedValue?: E): Matcher<T>;

194

}

195

196

interface MatcherLike<T> {

197

asymmetricMatch(other: unknown): boolean;

198

toString(): string;

199

getExpectedType?(): string;

200

toAsymmetricMatcher?(): string;

201

}

202

203

class Matcher<T> implements MatcherLike<T> {

204

$$typeof: symbol;

205

inverse?: boolean;

206

207

constructor(readonly asymmetricMatch: MatcherFn<T>, readonly description: string);

208

toString(): string;

209

toAsymmetricMatcher(): string;

210

getExpectedType(): string;

211

}

212

213

class CaptorMatcher<T> {

214

$$typeof: symbol;

215

readonly asymmetricMatch: MatcherFn<T>;

216

readonly value: T;

217

readonly values: T[];

218

219

constructor();

220

getExpectedType(): string;

221

toString(): string;

222

toAsymmetricMatcher(): string;

223

}

224

225

type ProxiedProperty = string | number | symbol;

226

227

// From jest-mock dependency

228

type FunctionLike = (...args: any[]) => any;

229

230

type _MockProxy<T> = {

231

[K in keyof T]: T[K] extends FunctionLike

232

? T[K] & CalledWithMock<T[K]>

233

: T[K];

234

};

235

236

type MockProxy<T> = _MockProxy<T> & T;

237

238

type _DeepMockProxy<T> = {

239

[K in keyof T]: T[K] extends FunctionLike

240

? T[K] & CalledWithMock<T[K]>

241

: T[K] & _DeepMockProxy<T[K]>;

242

};

243

244

type DeepMockProxy<T> = _DeepMockProxy<T> & T;

245

246

type _DeepMockProxyWithFuncPropSupport<T> = {

247

[K in keyof T]: T[K] extends FunctionLike

248

? CalledWithMock<T[K]> & DeepMockProxy<T[K]>

249

: DeepMockProxy<T[K]>;

250

};

251

252

type DeepMockProxyWithFuncPropSupport<T> = _DeepMockProxyWithFuncPropSupport<T> & T;

253

```