or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-jest-matcher-utils

A set of utility functions for expect and related packages

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/jest-matcher-utils@30.1.x

To install, run

npx @tessl/cli install tessl/npm-jest-matcher-utils@30.1.0

0

# Jest Matcher Utils

1

2

Jest Matcher Utils is a TypeScript utility library that provides essential functions for Jest's expect assertion library and related testing packages. It offers comprehensive formatting, styling, comparison, and validation functions for creating clear and informative test failure messages.

3

4

## Package Information

5

6

- **Package Name**: jest-matcher-utils

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install jest-matcher-utils` (typically installed as part of Jest)

10

11

## Core Imports

12

13

```typescript

14

import {

15

stringify,

16

printReceived,

17

printExpected,

18

matcherHint,

19

matcherErrorMessage,

20

diff,

21

EXPECTED_COLOR,

22

RECEIVED_COLOR,

23

INVERTED_COLOR,

24

BOLD_WEIGHT,

25

DIM_COLOR,

26

SUGGEST_TO_CONTAIN_EQUAL,

27

SERIALIZABLE_PROPERTIES,

28

type MatcherHintOptions,

29

type DiffOptions

30

} from "jest-matcher-utils";

31

```

32

33

For CommonJS:

34

35

```javascript

36

const {

37

stringify,

38

printReceived,

39

printExpected,

40

matcherHint,

41

matcherErrorMessage,

42

diff,

43

EXPECTED_COLOR,

44

RECEIVED_COLOR,

45

INVERTED_COLOR,

46

BOLD_WEIGHT,

47

DIM_COLOR,

48

SUGGEST_TO_CONTAIN_EQUAL,

49

SERIALIZABLE_PROPERTIES

50

} = require("jest-matcher-utils");

51

```

52

53

## Basic Usage

54

55

```typescript

56

import {

57

matcherHint,

58

matcherErrorMessage,

59

printReceived,

60

printExpected,

61

diff,

62

printWithType,

63

ensureNumbers,

64

EXPECTED_COLOR,

65

RECEIVED_COLOR

66

} from "jest-matcher-utils";

67

68

// Custom matcher example

69

function toBeGreaterThan(received: unknown, expected: unknown) {

70

// Validate inputs

71

ensureNumbers(received, expected, 'toBeGreaterThan');

72

73

const pass = (received as number) > (expected as number);

74

const hint = matcherHint('toBeGreaterThan', 'received', 'expected');

75

76

if (!pass) {

77

const diffOutput = diff(expected, received);

78

const message = matcherErrorMessage(

79

hint,

80

`Expected value to be greater than ${EXPECTED_COLOR(String(expected))}`,

81

diffOutput || `Received: ${printReceived(received)}`

82

);

83

return { pass, message: () => message };

84

}

85

86

return { pass, message: () => '' };

87

}

88

89

// Using formatting functions

90

const value = { name: 'Alice', age: 25 };

91

console.log(printReceived(value)); // Red-colored output

92

console.log(printExpected(value)); // Green-colored output

93

```

94

95

## Architecture

96

97

Jest Matcher Utils is organized around several core areas:

98

99

- **Formatting Functions**: Convert objects to styled string representations (`stringify`, `printReceived`, `printExpected`)

100

- **Display Utilities**: Create consistent test output formatting (`matcherHint`, `getLabelPrinter`, `pluralize`)

101

- **Validation Functions**: Ensure proper types for matcher operations (`ensureNumbers`, `ensureActualIsNumber`)

102

- **Diff Generation**: Compare and visualize differences between values (`diff`, `printDiffOrStringify`)

103

- **Error Handling**: Create informative error messages for test failures (`matcherErrorMessage`)

104

- **Style Constants**: Predefined color and formatting functions (`EXPECTED_COLOR`, `RECEIVED_COLOR`)

105

106

## Capabilities

107

108

### Value Formatting

109

110

Core functions for converting objects to formatted string representations with proper styling and whitespace handling.

111

112

```typescript { .api }

113

/**

114

* Convert objects to string representation with formatting

115

*/

116

function stringify(

117

object: unknown,

118

maxDepth?: number,

119

maxWidth?: number

120

): string;

121

122

/**

123

* Format received values with red color and whitespace indicators

124

*/

125

function printReceived(object: unknown): string;

126

127

/**

128

* Format expected values with green color and whitespace indicators

129

*/

130

function printExpected(value: unknown): string;

131

132

/**

133

* Highlight trailing whitespace in text with inverse colors

134

*/

135

function highlightTrailingWhitespace(text: string): string;

136

137

/**

138

* Print value with its type information

139

*/

140

function printWithType<T>(

141

name: string,

142

value: T,

143

print: (value: T) => string

144

): string;

145

```

146

147

[Value Formatting](./value-formatting.md)

148

149

### Matcher Display

150

151

Functions for creating consistent matcher hints and error messages in test output.

152

153

```typescript { .api }

154

/**

155

* Generate hint display for matcher assertions

156

*/

157

function matcherHint(

158

matcherName: string,

159

received?: string,

160

expected?: string,

161

options?: MatcherHintOptions

162

): string;

163

164

/**

165

* Create formatted error message for matcher failures

166

*/

167

function matcherErrorMessage(

168

hint: string,

169

generic: string,

170

specific?: string

171

): string;

172

173

/**

174

* Create a function that formats labels with consistent alignment

175

*/

176

function getLabelPrinter(...strings: Array<string>): PrintLabel;

177

178

/**

179

* Pluralize a word based on count

180

*/

181

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

182

183

interface MatcherHintOptions {

184

comment?: string;

185

expectedColor?: MatcherHintColor;

186

isDirectExpectCall?: boolean;

187

isNot?: boolean;

188

promise?: string;

189

receivedColor?: MatcherHintColor;

190

secondArgument?: string;

191

secondArgumentColor?: MatcherHintColor;

192

}

193

194

type PrintLabel = (string: string) => string;

195

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

196

```

197

198

[Matcher Display](./matcher-display.md)

199

200

### Value Validation

201

202

Functions for validating types and values in matcher operations.

203

204

```typescript { .api }

205

/**

206

* Validate that matcher doesn't receive an expected argument

207

*/

208

function ensureNoExpected(

209

expected: unknown,

210

matcherName: string,

211

options?: MatcherHintOptions

212

): void;

213

214

/**

215

* Validate that actual value is a number or bigint

216

*/

217

function ensureActualIsNumber(

218

actual: unknown,

219

matcherName: string,

220

options?: MatcherHintOptions

221

): void;

222

223

/**

224

* Validate that expected value is a number or bigint

225

*/

226

function ensureExpectedIsNumber(

227

expected: unknown,

228

matcherName: string,

229

options?: MatcherHintOptions

230

): void;

231

232

/**

233

* Validate that both actual and expected values are numbers or bigints

234

*/

235

function ensureNumbers(

236

actual: unknown,

237

expected: unknown,

238

matcherName: string,

239

options?: MatcherHintOptions

240

): void;

241

242

/**

243

* Validate that expected value is a non-negative integer

244

*/

245

function ensureExpectedIsNonNegativeInteger(

246

expected: unknown,

247

matcherName: string,

248

options?: MatcherHintOptions

249

): void;

250

```

251

252

[Value Validation](./value-validation.md)

253

254

### Diff Generation

255

256

Functions for comparing values and generating visual diffs for test output.

257

258

```typescript { .api }

259

/**

260

* Generate diff between two values

261

*/

262

function diff(

263

a: unknown,

264

b: unknown,

265

options?: DiffOptions

266

): string | null;

267

268

/**

269

* Generate diff output or stringify values for comparison

270

*/

271

function printDiffOrStringify(

272

expected: unknown,

273

received: unknown,

274

expectedLabel: string,

275

receivedLabel: string,

276

expand: boolean

277

): string;

278

279

/**

280

* Replace matched values with asymmetric matchers for comparison

281

*/

282

function replaceMatchedToAsymmetricMatcher(

283

replacedExpected: unknown,

284

replacedReceived: unknown,

285

expectedCycles: Array<unknown>,

286

receivedCycles: Array<unknown>

287

): {replacedExpected: unknown; replacedReceived: unknown};

288

289

type DiffOptions = {

290

aAnnotation?: string;

291

bAnnotation?: string;

292

changeColor?: (arg: string) => string;

293

changeLineTrailingSpaceColor?: (arg: string) => string;

294

commonColor?: (arg: string) => string;

295

commonLineTrailingSpaceColor?: (arg: string) => string;

296

contextLines?: number;

297

expand?: boolean;

298

includeChangeCounts?: boolean;

299

omitAnnotationLines?: boolean;

300

patchColor?: (arg: string) => string;

301

};

302

```

303

304

[Diff Generation](./diff-generation.md)

305

306

## Style Constants

307

308

```typescript { .api }

309

/** Green color for expected values in test output */

310

const EXPECTED_COLOR: Chalk;

311

312

/** Red color for received values in test output */

313

const RECEIVED_COLOR: Chalk;

314

315

/** Inverse color formatting */

316

const INVERTED_COLOR: Chalk;

317

318

/** Bold text formatting */

319

const BOLD_WEIGHT: Chalk;

320

321

/** Dim text formatting for secondary elements */

322

const DIM_COLOR: Chalk;

323

324

/** Suggestion message for using toContainEqual instead of toContain */

325

const SUGGEST_TO_CONTAIN_EQUAL: string;

326

327

/** Symbol for marking serializable properties on objects */

328

const SERIALIZABLE_PROPERTIES: symbol;

329

```

330

331