or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

argument-matching.mdbasic-mocking.mddeep-mocking.mdindex.mdmatchers.mdutilities.md
tile.json

basic-mocking.mddocs/

0

# Basic Mocking

1

2

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

3

4

## Capabilities

5

6

### Mock Function

7

8

Creates a type-safe mock proxy for any interface or class, preserving TypeScript type information while adding Jest mock functionality.

9

10

```typescript { .api }

11

/**

12

* Creates a type-safe mock proxy for interfaces and classes

13

* @param mockImplementation - Optional partial implementation to override default behavior

14

* @param opts - Configuration options for mock behavior

15

* @returns Type-safe mock proxy with Jest functionality

16

*/

17

function mock<T>(

18

mockImplementation?: DeepPartial<T>,

19

opts?: MockOpts

20

): MockProxy<T> & T;

21

22

interface MockOpts {

23

/** Enable deep mocking for nested objects */

24

deep?: boolean;

25

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

26

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

27

}

28

```

29

30

**Usage Examples:**

31

32

```typescript

33

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

34

35

interface PaymentService {

36

processPayment: (amount: number, cardId: string) => Promise<PaymentResult>;

37

validateCard: (cardId: string) => boolean;

38

refundPayment: (paymentId: string) => Promise<void>;

39

}

40

41

// Basic mock creation

42

const paymentService = mock<PaymentService>();

43

44

// Mock with partial implementation

45

const paymentServiceWithDefaults = mock<PaymentService>({

46

validateCard: jest.fn().mockReturnValue(true)

47

});

48

49

// Mock with fallback implementation

50

const strictPaymentService = mock<PaymentService>({}, {

51

fallbackMockImplementation: () => {

52

throw new Error("Mock not configured for this call");

53

}

54

});

55

```

56

57

### MockProxy Type

58

59

Type definition that adds calledWith extension to function properties while preserving original type structure.

60

61

```typescript { .api }

62

/**

63

* Type-safe mock proxy that extends original type with Jest mock functionality

64

*/

65

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

66

67

type _MockProxy<T> = {

68

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

69

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

70

: T[K];

71

};

72

```

73

74

**Usage Examples:**

75

76

```typescript

77

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

78

79

interface DatabaseService {

80

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

81

saveUser: (user: User) => Promise<void>;

82

}

83

84

// Properly typed mock variable

85

let dbService: MockProxy<DatabaseService>;

86

87

beforeEach(() => {

88

dbService = mock<DatabaseService>();

89

});

90

91

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

92

// Full type safety and calledWith functionality

93

dbService.saveUser.calledWith(expect.any(Object)).mockResolvedValue();

94

95

await dbService.saveUser({ id: "123", name: "John" });

96

97

expect(dbService.saveUser).toHaveBeenCalledWith({ id: "123", name: "John" });

98

});

99

```

100

101

### CalledWithMock Interface

102

103

Extended Jest mock interface that adds argument-specific expectation functionality through the calledWith method.

104

105

```typescript { .api }

106

/**

107

* Jest mock extended with argument-specific expectations

108

*/

109

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

110

/**

111

* Creates argument-specific expectation for mock function

112

* @param args - Expected arguments (can use matchers or literal values)

113

* @returns Jest mock for chaining expectations

114

*/

115

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

116

}

117

```

118

119

**Usage Examples:**

120

121

```typescript

122

import { mock, any, anyString } from "jest-mock-extended";

123

124

interface EmailService {

125

sendEmail: (to: string, subject: string, body: string) => Promise<boolean>;

126

}

127

128

const emailService = mock<EmailService>();

129

130

// Argument-specific expectations

131

emailService.sendEmail

132

.calledWith("admin@example.com", anyString(), any())

133

.mockResolvedValue(true);

134

135

emailService.sendEmail

136

.calledWith("invalid@email", any(), any())

137

.mockResolvedValue(false);

138

139

// Test behavior

140

expect(await emailService.sendEmail("admin@example.com", "Hello", "World")).toBe(true);

141

expect(await emailService.sendEmail("invalid@email", "Test", "Body")).toBe(false);

142

```

143

144

### Mock Function Creator

145

146

Creates a standalone Jest function mock with calledWith extension, useful for mocking individual functions.

147

148

```typescript { .api }

149

/**

150

* Creates a Jest function mock with calledWith extension

151

* @returns Typed mock function with argument matching capabilities

152

*/

153

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

154

```

155

156

**Usage Examples:**

157

158

```typescript

159

import { mockFn } from "jest-mock-extended";

160

161

type CalculatorFn = (a: number, b: number) => number;

162

163

// Create standalone function mock

164

const calculateFn = mockFn<CalculatorFn>();

165

166

// Set up argument-specific behavior

167

calculateFn.calledWith(1, 2).mockReturnValue(3);

168

calculateFn.calledWith(5, 5).mockReturnValue(10);

169

170

// Use in tests

171

expect(calculateFn(1, 2)).toBe(3);

172

expect(calculateFn(5, 5)).toBe(10);

173

expect(calculateFn).toHaveBeenCalledTimes(2);

174

```