or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ajax-mocking.mddata-generation.mddata-validation.mdindex.mdrandom-data.mdutilities.md

index.mddocs/

0

# Mock.js

1

2

Mock.js is a comprehensive JavaScript library that enables developers to generate simulated data according to data templates and intercept Ajax requests. It provides an intuitive syntax for data generation, supports various data types with flexible generation rules, and includes Ajax request/response mocking functionality that works with popular libraries like jQuery.

3

4

## Package Information

5

6

- **Package Name**: mockjs

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install mockjs`

10

11

## Core Imports

12

13

```javascript

14

const Mock = require('mockjs');

15

```

16

17

For ES modules:

18

19

```javascript

20

import Mock from 'mockjs';

21

```

22

23

Browser usage (UMD):

24

25

```html

26

<script src="path/to/mock.js"></script>

27

<!-- Now available as global Mock -->

28

```

29

30

## Basic Usage

31

32

```javascript

33

const Mock = require('mockjs');

34

35

// Generate data from template

36

const data = Mock.mock({

37

'list|1-10': [{

38

'id|+1': 1,

39

'name': '@name',

40

'email': '@email',

41

'address': '@city @county'

42

}]

43

});

44

45

// Mock Ajax requests

46

Mock.mock('/api/users', 'get', {

47

'users|5-10': [{

48

'id|+1': 1,

49

'name': '@name',

50

'age|18-60': 1

51

}]

52

});

53

54

// Generate individual random values

55

const randomName = Mock.mock('@name');

56

const randomEmail = Mock.mock('@email');

57

```

58

59

## Architecture

60

61

Mock.js is built around several key components:

62

63

- **Template Engine**: Processes data templates with generation rules using `Mock.mock()`

64

- **Random Data Generators**: Extensive collection of functions for generating realistic fake data (`Mock.Random`)

65

- **Ajax Interception**: XMLHttpRequest mocking system for intercepting and responding to requests (`Mock.setup()`)

66

- **Validation System**: Schema validation to verify real data against templates (`Mock.valid()`)

67

- **Utility Functions**: Helper functions for common operations (`Mock.Util`)

68

69

## Capabilities

70

71

### Data Generation

72

73

Core template-based data generation using rule syntax for creating realistic mock data structures. Perfect for testing, development, and prototyping.

74

75

```javascript { .api }

76

/**

77

* Generate mock data from a template

78

* @param template - Data template with optional generation rules

79

* @returns Generated mock data

80

*/

81

Mock.mock(template: any): any;

82

83

/**

84

* Generate mock data from template with name context

85

* @param template - Data template

86

* @param name - Property name for rule context

87

* @returns Generated mock data

88

*/

89

Mock.mock(template: any, name: string): any;

90

```

91

92

[Data Generation](./data-generation.md)

93

94

### Random Data Functions

95

96

Extensive collection of random data generators for creating realistic fake data including names, addresses, dates, images, and more.

97

98

```javascript { .api }

99

/**

100

* Random data generator object containing all generator functions

101

*/

102

Mock.Random: {

103

// Basic types

104

boolean(min?: number, max?: number, current?: boolean): boolean;

105

natural(min?: number, max?: number): number;

106

integer(min?: number, max?: number): number;

107

float(min?: number, max?: number, dmin?: number, dmax?: number): number;

108

character(pool?: string): string;

109

string(pool?: string, min?: number, max?: number): string;

110

111

// Common data generators

112

name(middle?: boolean): string;

113

email(domain?: string): string;

114

url(protocol?: string, host?: string): string;

115

date(format?: string): string;

116

image(size?: string, background?: string, text?: string): string;

117

118

// Helper functions

119

pick(array: any[], min?: number, max?: number): any;

120

shuffle(array: any[]): any[];

121

}

122

```

123

124

[Random Data](./random-data.md)

125

126

### Ajax Request Mocking

127

128

XMLHttpRequest interception system for mocking HTTP requests and responses, enabling independent frontend development.

129

130

```javascript { .api }

131

/**

132

* Mock HTTP requests by URL pattern

133

* @param url - Request URL pattern (string or RegExp)

134

* @param template - Response data template

135

* @returns Mock instance for chaining

136

*/

137

Mock.mock(url: string | RegExp, template: any): typeof Mock;

138

139

/**

140

* Mock HTTP requests by URL pattern and method

141

* @param url - Request URL pattern (string or RegExp)

142

* @param method - HTTP method (get, post, put, delete, etc.)

143

* @param template - Response data template or function

144

* @returns Mock instance for chaining

145

*/

146

Mock.mock(url: string | RegExp, method: string, template: any | Function): typeof Mock;

147

148

/**

149

* Configure XMLHttpRequest mock behavior

150

* @param settings - Configuration options

151

*/

152

Mock.setup(settings: {

153

timeout?: string;

154

onAfterResponse?: Function;

155

}): void;

156

```

157

158

[Ajax Mocking](./ajax-mocking.md)

159

160

### Data Validation

161

162

Validation system for verifying that real data matches specified templates, useful for API contract testing.

163

164

```javascript { .api }

165

/**

166

* Validate data against a template schema

167

* @param template - Data template schema

168

* @param data - Real data to validate

169

* @returns Array of validation errors (empty if valid)

170

*/

171

Mock.valid(template: any, data: any): ValidationError[];

172

173

interface ValidationError {

174

path: string[];

175

type: string;

176

message: string;

177

expected: any;

178

actual: any;

179

}

180

```

181

182

[Data Validation](./data-validation.md)

183

184

### JSON Schema Conversion

185

186

Convert Mock.js templates to JSON Schema format for external validation systems.

187

188

```javascript { .api }

189

/**

190

* Convert Mock.js template to JSON Schema

191

* @param template - Mock.js data template

192

* @returns JSON Schema representation of the template

193

*/

194

Mock.toJSONSchema(template: any): any;

195

```

196

197

**Usage Examples:**

198

199

```javascript

200

const template = {

201

'list|1-10': [{

202

'id|+1': 1,

203

name: '@name',

204

'age|18-65': 1

205

}]

206

};

207

208

const schema = Mock.toJSONSchema(template);

209

// Generated JSON Schema can be used with external validators

210

```

211

212

### Utility Functions

213

214

Common utility functions for object manipulation, type checking, and string processing.

215

216

```javascript { .api }

217

Mock.Util: {

218

extend(target: any, ...sources: any[]): any;

219

each(obj: any, iterator: Function, context?: any): void;

220

type(obj: any): string;

221

keys(obj: any): string[];

222

values(obj: any): any[];

223

heredoc(fn: Function): string;

224

}

225

```

226

227

[Utilities](./utilities.md)

228

229

## Types

230

231

```javascript { .api }

232

// Template generation rules use | syntax

233

interface TemplateRule {

234

// 'property|rule': value

235

// Examples:

236

// 'list|1-10': [] - generate 1-10 items

237

// 'id|+1': 1 - auto-increment starting from 1

238

// 'name|3': 'x' - repeat string 3 times

239

// 'flag|1-2': true - boolean with probability ratio

240

}

241

242

// Placeholder strings use @ syntax

243

interface PlaceholderString {

244

// '@function' or '@function(args)'

245

// Examples: '@name', '@email', '@date(yyyy-MM-dd)'

246

}

247

```