or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md
tile.json

index.mddocs/

0

# @jest/expect

1

2

@jest/expect extends the core `expect` assertion library with Jest's powerful snapshot testing capabilities. It provides a drop-in replacement for the standard `expect` function that includes all core functionality plus specialized snapshot matchers for testing complex data structures and error outputs.

3

4

## Package Information

5

6

- **Package Name**: @jest/expect

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @jest/expect`

10

11

## Core Imports

12

13

```typescript

14

import { jestExpect } from "@jest/expect";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { jestExpect } = require("@jest/expect");

21

```

22

23

Type imports:

24

25

```typescript

26

import type {

27

JestExpect,

28

AsymmetricMatchers,

29

Matchers,

30

MatcherContext,

31

MatcherFunction,

32

MatcherFunctionWithContext,

33

MatcherState,

34

MatcherUtils

35

} from "@jest/expect";

36

```

37

38

## Basic Usage

39

40

```typescript

41

import { jestExpect } from "@jest/expect";

42

43

// Use as drop-in replacement for expect

44

const user = { name: "Alice", age: 25, settings: { theme: "dark" } };

45

46

// Standard expect functionality works

47

jestExpect(user.name).toBe("Alice");

48

jestExpect(user.age).toBeGreaterThan(18);

49

50

// Snapshot testing for complex objects

51

jestExpect(user).toMatchSnapshot();

52

53

// Inline snapshots

54

jestExpect(user.settings).toMatchInlineSnapshot(`

55

{

56

"theme": "dark"

57

}

58

`);

59

60

// Error snapshot testing

61

const throwingFunction = () => {

62

throw new Error("Something went wrong");

63

};

64

65

jestExpect(throwingFunction).toThrowErrorMatchingSnapshot();

66

```

67

68

## Architecture

69

70

@jest/expect is built as a lightweight bridge between two core Jest libraries:

71

72

- **Core Foundation**: Built on the `expect` assertion library that provides all standard matchers, asymmetric matchers, and core assertion functionality

73

- **Snapshot Extension**: Integrates `jest-snapshot` to add specialized snapshot testing matchers and serialization capabilities

74

- **Unified Interface**: Exports a single `jestExpect` function that combines both libraries into one cohesive API

75

- **Plugin System**: Supports custom snapshot serializers through the `addSnapshotSerializer` method for formatting specific data types

76

77

The package acts as an enhanced drop-in replacement for the standard `expect` function, maintaining full compatibility while adding Jest's powerful snapshot testing features.

78

79

## Capabilities

80

81

### Core Expect Function

82

83

Enhanced expect function with full compatibility with standard expect plus snapshot testing capabilities.

84

85

```typescript { .api }

86

/**

87

* Enhanced expect function with snapshot testing capabilities

88

* @param actual - The value to make assertions against

89

* @returns Matcher object with all standard and snapshot matchers

90

*/

91

function jestExpect<T = unknown>(

92

actual: T

93

): JestMatchers<void, T> &

94

Inverse<JestMatchers<void, T>> &

95

PromiseMatchers<T>;

96

```

97

98

### Snapshot Matchers

99

100

#### Match Snapshot

101

102

Compare received value against stored snapshot file.

103

104

```typescript { .api }

105

/**

106

* Compare value against stored snapshot

107

* @param hint - Optional hint for snapshot name

108

* @returns Matcher result

109

*/

110

toMatchSnapshot(hint?: string): void;

111

112

/**

113

* Compare value against stored snapshot with property matchers

114

* @param propertyMatchers - Matchers for specific object properties

115

* @param hint - Optional hint for snapshot name

116

* @returns Matcher result

117

*/

118

toMatchSnapshot<U extends Record<keyof T, unknown>>(

119

propertyMatchers: Partial<U>,

120

hint?: string

121

): void;

122

```

123

124

#### Match Inline Snapshot

125

126

Compare received value against inline snapshot in source code.

127

128

```typescript { .api }

129

/**

130

* Compare value against inline snapshot in source code

131

* @param snapshot - Optional inline snapshot string

132

* @returns Matcher result

133

*/

134

toMatchInlineSnapshot(snapshot?: string): void;

135

136

/**

137

* Compare value against inline snapshot with property matchers

138

* @param propertyMatchers - Matchers for specific object properties

139

* @param snapshot - Optional inline snapshot string

140

* @returns Matcher result

141

*/

142

toMatchInlineSnapshot<U extends Record<keyof T, unknown>>(

143

propertyMatchers: Partial<U>,

144

snapshot?: string

145

): void;

146

```

147

148

#### Error Snapshot Matchers

149

150

Test that functions throw errors matching stored or inline snapshots.

151

152

```typescript { .api }

153

/**

154

* Test that function throws error matching stored snapshot

155

* @param hint - Optional hint for snapshot name

156

* @returns Matcher result

157

*/

158

toThrowErrorMatchingSnapshot(hint?: string): void;

159

160

/**

161

* Test that function throws error matching inline snapshot

162

* @param snapshot - Optional inline snapshot string

163

* @returns Matcher result

164

*/

165

toThrowErrorMatchingInlineSnapshot(snapshot?: string): void;

166

```

167

168

### Promise Matchers

169

170

Enhanced promise testing with snapshot support.

171

172

```typescript { .api }

173

interface PromiseMatchers<T = unknown> {

174

/**

175

* Unwraps the reason of a rejected promise so any other matcher can be chained.

176

* If the promise is fulfilled the assertion fails.

177

*/

178

rejects: JestMatchers<Promise<void>, T> & Inverse<JestMatchers<Promise<void>, T>>;

179

180

/**

181

* Unwraps the value of a fulfilled promise so any other matcher can be chained.

182

* If the promise is rejected the assertion fails.

183

*/

184

resolves: JestMatchers<Promise<void>, T> & Inverse<JestMatchers<Promise<void>, T>>;

185

}

186

```

187

188

**Usage Examples:**

189

190

```typescript

191

// Test rejected promise with snapshot

192

await jestExpect(Promise.reject(new Error("Failed")))

193

.rejects.toThrowErrorMatchingSnapshot();

194

195

// Test resolved promise value

196

await jestExpect(Promise.resolve({ success: true }))

197

.resolves.toMatchSnapshot();

198

```

199

200

### Snapshot Serializer Management

201

202

Add custom serializers for snapshot formatting.

203

204

```typescript { .api }

205

/**

206

* Add custom snapshot serializer for specific data types

207

* @param plugin - Pretty format plugin (NewPlugin or OldPlugin)

208

*/

209

jestExpect.addSnapshotSerializer(plugin: Plugin): void;

210

211

/**

212

* Pretty format plugin interface - modern format

213

*/

214

interface NewPlugin {

215

/** Test if serializer should handle this value */

216

test(val: any): boolean;

217

/** Serialize the value to string representation */

218

serialize(

219

val: any,

220

config: Config,

221

indentation: string,

222

depth: number,

223

refs: Refs,

224

printer: Printer

225

): string;

226

}

227

228

/**

229

* Pretty format plugin interface - legacy format

230

*/

231

interface OldPlugin {

232

/** Test if serializer should handle this value */

233

test(val: any): boolean;

234

/** Print the value using legacy format */

235

print(

236

val: unknown,

237

print: Print,

238

indent: Indent,

239

options: PluginOptions,

240

colors: Colors

241

): string;

242

}

243

244

/**

245

* Plugin can be either modern or legacy format

246

*/

247

type Plugin = NewPlugin | OldPlugin;

248

```

249

250

**Usage Examples:**

251

252

```typescript

253

// Add custom serializer for Date objects (NewPlugin format)

254

jestExpect.addSnapshotSerializer({

255

test: (val) => val instanceof Date,

256

serialize: (val, config, indentation, depth, refs, printer) =>

257

`Date("${val.toISOString()}")`,

258

});

259

260

// Or using legacy format (OldPlugin)

261

jestExpect.addSnapshotSerializer({

262

test: (val) => val instanceof Date,

263

print: (val, print, indent, options, colors) =>

264

`Date("${val.toISOString()}")`,

265

});

266

267

// Now Date objects will be formatted consistently in snapshots

268

jestExpect(new Date('2023-01-01')).toMatchSnapshot();

269

```

270

271

## Types

272

273

```typescript { .api }

274

/**

275

* Main JestExpect interface extending BaseExpect with snapshot capabilities

276

*/

277

type JestExpect = {

278

<T = unknown>(

279

actual: T,

280

): JestMatchers<void, T> &

281

Inverse<JestMatchers<void, T>> &

282

PromiseMatchers<T>;

283

addSnapshotSerializer: typeof addSerializer;

284

} & BaseExpect &

285

AsymmetricMatchers &

286

Inverse<Omit<AsymmetricMatchers, 'any' | 'anything'>>;

287

288

/**

289

* Combined matchers including core expect matchers and snapshot matchers

290

*/

291

type JestMatchers<R extends void | Promise<void>, T> = Matchers<R, T> & SnapshotMatchers<R, T>;

292

293

/**

294

* Asymmetric matcher utilities from expect

295

*/

296

interface AsymmetricMatchers {

297

any(sample: unknown): AsymmetricMatcher<unknown>;

298

anything(): AsymmetricMatcher<unknown>;

299

arrayContaining<E = unknown>(sample: readonly E[]): AsymmetricMatcher<unknown>;

300

objectContaining<E = {}>(sample: E): AsymmetricMatcher<unknown>;

301

stringContaining(sample: string): AsymmetricMatcher<unknown>;

302

stringMatching(sample: string | RegExp): AsymmetricMatcher<unknown>;

303

}

304

305

/**

306

* Core matcher context provided to matcher functions

307

*/

308

interface MatcherContext {

309

dontThrow?(): void;

310

isNot: boolean;

311

promise: string;

312

}

313

314

/**

315

* State object containing matcher execution information

316

*/

317

interface MatcherState {

318

assertionCalls: number;

319

currentTestName?: string;

320

expand?: boolean;

321

expectedAssertionsNumber?: number | null;

322

expectedAssertionsNumberError?: Error;

323

isExpectingAssertions?: boolean;

324

isExpectingAssertionsError?: Error;

325

isNot: boolean;

326

promise: string;

327

suppressedErrors: Error[];

328

testPath?: string;

329

snapshotState: SnapshotState;

330

testFailing?: boolean;

331

}

332

333

/**

334

* Utility functions available to matcher implementations

335

*/

336

interface MatcherUtils {

337

customTesters: Array<any>;

338

dontThrow(): void;

339

equals(a: unknown, b: unknown): boolean;

340

utils: {

341

diff(a: unknown, b: unknown): string | null;

342

ensureNoExpected(expected: unknown, matcherName: string): void;

343

ensureNumbers(actual: unknown, expected: unknown, matcherName: string): void;

344

matcherErrorMessage(hint: string, generic: string, specific: string): string;

345

matcherHint(matcherName: string, received?: string, expected?: string): string;

346

pluralize(word: string, count: number): string;

347

printExpected(value: unknown): string;

348

printReceived(value: unknown): string;

349

printWithType(name: string, value: unknown, print: (value: unknown) => string): string;

350

stringify(object: unknown): string;

351

EXPECTED_COLOR(text: string): string;

352

RECEIVED_COLOR(text: string): string;

353

};

354

}

355

356

/**

357

* Base matcher function signature

358

*/

359

type MatcherFunction<State extends MatcherState = MatcherState> = (

360

this: MatcherContext & MatcherUtils & State,

361

received: unknown,

362

expected: unknown,

363

...args: unknown[]

364

) => any;

365

366

/**

367

* Matcher function that explicitly receives context

368

*/

369

type MatcherFunctionWithContext<

370

State extends MatcherState = MatcherState,

371

Context extends MatcherContext = MatcherContext

372

> = (

373

this: MatcherUtils & State,

374

context: Context,

375

received: unknown,

376

expected: unknown,

377

...args: unknown[]

378

) => any;

379

380

/**

381

* Supporting types for plugin system

382

*/

383

type Refs = Array<unknown>;

384

type Print = (arg: unknown) => string;

385

type Indent = (arg: string) => string;

386

type Printer = (

387

val: unknown,

388

config: Config,

389

indentation: string,

390

depth: number,

391

refs: Refs,

392

hasCalledToJSON?: boolean

393

) => string;

394

395

interface Config {

396

callToJSON: boolean;

397

colors: Colors;

398

escapeRegex: boolean;

399

escapeString: boolean;

400

indent: string;

401

maxDepth: number;

402

maxWidth: number;

403

min: boolean;

404

plugins: Plugin[];

405

printFunctionName: boolean;

406

spacingInner: string;

407

spacingOuter: string;

408

}

409

410

interface Colors {

411

comment: { close: string; open: string };

412

content: { close: string; open: string };

413

prop: { close: string; open: string };

414

tag: { close: string; open: string };

415

value: { close: string; open: string };

416

}

417

418

interface PluginOptions {

419

edgeSpacing: string;

420

min: boolean;

421

spacing: string;

422

}

423

```