333
schangxiang@126.com
2025-09-19 18966e02fb573c7e2bb0c6426ed792b38b910940
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
'use strict';
 
const debug = require('debug')('egg-mock:application');
const mm = require('mm');
const http = require('http');
const fs = require('fs');
const merge = require('merge-descriptors');
const is = require('is-type-of');
const assert = require('assert');
const Transport = require('egg-logger').Transport;
const mockHttpclient = require('../../lib/mock_httpclient');
const supertestRequest = require('../../lib/supertest');
 
const ORIGIN_TYPES = Symbol('egg-mock:originTypes');
const BACKGROUND_TASKS = Symbol('Application#backgroundTasks');
 
module.exports = {
  /**
   * mock Context
   * @function App#mockContext
   * @param {Object} data - ctx data
   * @return {Context} ctx
   * @example
   * ```js
   * const ctx = app.mockContext({
   *   user: {
   *     name: 'Jason'
   *   }
   * });
   * console.log(ctx.user.name); // Jason
   *
   * // controller
   * module.exports = function*() {
   *   this.body = this.user.name;
   * };
   * ```
   */
  mockContext(data) {
    data = data || {};
 
    if (this._customMockContext) {
      this._customMockContext(data);
    }
 
    // 使用者自定义mock,可以覆盖上面的 mock
    for (const key in data) {
      mm(this.context, key, data[key]);
    }
 
    const req = this.mockRequest(data);
    const res = new http.ServerResponse(req);
 
    return this.createContext(req, res);
  },
 
  /**
   * mock cookie session
   * @function App#mockSession
   * @param {Object} data - session object
   * @return {App} this
   */
  mockSession(data) {
    if (!data) {
      return this;
    }
 
    if (is.object(data) && !data.save) {
      Object.defineProperty(data, 'save', {
        value: () => {},
        enumerable: false,
      });
    }
    mm(this.context, 'session', data);
    return this;
  },
 
  /**
   * Mock service
   * @function App#mockService
   * @param {String} service - name
   * @param {String} methodName - method
   * @param {Object/Function/Error} fn - mock you data
   * @return {App} this
   */
  mockService(service, methodName, fn) {
    if (typeof service === 'string') {
      const arr = service.split('.');
      service = this.serviceClasses;
      for (const key of arr) {
        service = service[key];
      }
      service = service.prototype || service;
    }
    this._mockFn(service, methodName, fn);
    return this;
  },
 
  /**
   * mock service that return error
   * @function App#mockServiceError
   * @param {String} service - name
   * @param {String} methodName - method
   * @param {Error} [err] - error infomation
   * @return {App} this
   */
  mockServiceError(service, methodName, err) {
    if (typeof err === 'string') {
      err = new Error(err);
    } else if (!err) {
      // mockServiceError(service, methodName)
      err = new Error('mock ' + methodName + ' error');
    }
    this.mockService(service, methodName, err);
    return this;
  },
 
  _mockFn(obj, name, data) {
    const origin = obj[name];
    assert(is.function(origin), `property ${name} in original object must be function`);
 
    // keep origin properties' type to support mock multitimes
    if (!obj[ORIGIN_TYPES]) obj[ORIGIN_TYPES] = {};
    let type = obj[ORIGIN_TYPES][name];
    if (!type) {
      type = obj[ORIGIN_TYPES][name] = is.generatorFunction(origin) || is.asyncFunction(origin) ? 'async' : 'sync';
    }
 
    if (is.function(data)) {
      const fn = data;
      // if original is generator function or async function
      // but the mock function is normal function, need to change it return a promise
      if (type === 'async' &&
      (!is.generatorFunction(fn) && !is.asyncFunction(fn))) {
        mm(obj, name, function(...args) {
          return new Promise(resolve => {
            resolve(fn.apply(this, args));
          });
        });
        return;
      }
 
      mm(obj, name, fn);
      return;
    }
 
    if (type === 'async') {
      mm(obj, name, () => {
        return new Promise((resolve, reject) => {
          if (data instanceof Error) return reject(data);
          resolve(data);
        });
      });
      return;
    }
 
    mm(obj, name, () => {
      if (data instanceof Error) {
        throw data;
      }
      return data;
    });
  },
 
  /**
   * mock request
   * @function App#mockRequest
   * @param {Request} req - mock request
   * @return {Request} req
   */
  mockRequest(req) {
    req = Object.assign({}, req);
    const headers = req.headers || {};
    for (const key in req.headers) {
      headers[key.toLowerCase()] = req.headers[key];
    }
    if (!headers['x-forwarded-for']) {
      headers['x-forwarded-for'] = '127.0.0.1';
    }
    req.headers = headers;
    merge(req, {
      query: {},
      querystring: '',
      host: '127.0.0.1',
      hostname: '127.0.0.1',
      protocol: 'http',
      secure: 'false',
      method: 'GET',
      url: '/',
      path: '/',
      socket: {
        remoteAddress: '127.0.0.1',
        remotePort: 7001,
      },
    });
    return req;
  },
 
  /**
   * mock cookies
   * @function App#mockCookies
   * @param {Object} cookies - cookie
   * @return {Context} this
   */
  mockCookies(cookies) {
    if (!cookies) {
      return this;
    }
    const createContext = this.createContext;
    mm(this, 'createContext', function(req, res) {
      const ctx = createContext.call(this, req, res);
      const getCookie = ctx.cookies.get;
      mm(ctx.cookies, 'get', function(key, opts) {
        if (cookies[key]) {
          return cookies[key];
        }
        return getCookie.call(this, key, opts);
      });
      return ctx;
    });
    return this;
  },
 
  /**
   * mock header
   * @function App#mockHeaders
   * @param {Object} headers - header 对象
   * @return {Context} this
   */
  mockHeaders(headers) {
    if (!headers) {
      return this;
    }
    const getHeader = this.request.get;
    mm(this.request, 'get', function(field) {
      const header = findHeaders(headers, field);
      if (header) return header;
      return getHeader.call(this, field);
    });
    return this;
  },
 
  /**
   * mock csrf
   * @function App#mockCsrf
   * @return {App} this
   * @since 1.11
   */
  mockCsrf() {
    mm(this.context, 'assertCSRF', () => {});
    mm(this.context, 'assertCsrf', () => {});
    return this;
  },
 
  /**
   * mock httpclient
   * @function App#mockHttpclient
   * @param {...any} args - args
   * @return {Context} this
   */
  mockHttpclient(...args) {
    if (!this._mockHttpclient) {
      this._mockHttpclient = mockHttpclient(this);
    }
    return this._mockHttpclient(...args);
  },
 
  mockUrllib(...args) {
    this.deprecate('[egg-mock] Please use app.mockHttpclient instead of app.mockUrllib');
    return this.mockHttpclient(...args);
  },
 
  /**
   * @see mm#restore
   * @function App#mockRestore
   */
  mockRestore: mm.restore,
 
  /**
   * @see mm
   * @function App#mm
   */
  mm,
 
  /**
   * override loadAgent
   * @function App#loadAgent
   */
  loadAgent() {},
 
  /**
   * mock serverEnv
   * @function App#mockEnv
   * @param  {String} env - serverEnv
   * @return {App} this
   */
  mockEnv(env) {
    mm(this.config, 'env', env);
    mm(this.config, 'serverEnv', env);
    return this;
  },
 
  /**
   * http request helper
   * @function App#httpRequest
   * @return {SupertestRequest} req - supertest request
   * @see https://github.com/visionmedia/supertest
   */
  httpRequest() {
    return supertestRequest(this);
  },
 
  /**
   * collection logger message, then can be use on `expectLog()`
   * @param {String|Logger} [logger] - logger instance, default is `ctx.logger`
   * @function App#mockLog
   */
  mockLog(logger) {
    logger = logger || this.logger;
    if (typeof logger === 'string') {
      logger = this.getLogger(logger);
    }
    // make sure mock once
    if (logger._mockLogs) return;
 
    const transport = new Transport(logger.options);
    // https://github.com/eggjs/egg-logger/blob/master/lib/logger.js#L64
    const log = logger.log;
    mm(logger, '_mockLogs', []);
    mm(logger, 'log', (level, args, meta) => {
      const message = transport.log(level, args, meta);
      logger._mockLogs.push(message);
      log.apply(logger, [ level, args, meta ]);
    });
  },
 
  /**
   * expect str/regexp in the logger, if your server disk is slow, please call `mockLog()` first.
   * @param {String|RegExp} str - test str or regexp
   * @param {String|Logger} [logger] - logger instance, default is `ctx.logger`
   * @function App#expectLog
   */
  expectLog(str, logger) {
    logger = logger || this.logger;
    if (typeof logger === 'string') {
      logger = this.getLogger(logger);
    }
    const filepath = logger.options.file;
    let content;
    if (logger._mockLogs && logger._mockLogs.length > 0) {
      content = logger._mockLogs.join('\n');
    } else {
      content = fs.readFileSync(filepath, 'utf8');
    }
    if (str instanceof RegExp) {
      assert(str.test(content), `Can't find RegExp:"${str}" in ${filepath}, log content: ...${content.substring(content.length - 500)}`);
    } else {
      str = String(str);
      assert(content.includes(str), `Can't find String:"${str}" in ${filepath}, log content: ...${content.substring(content.length - 500)}`);
    }
  },
 
  // private method
  backgroundTasksFinished() {
    const tasks = this._backgroundTasks;
    debug('waiting %d background tasks', tasks.length);
    if (tasks.length === 0) return Promise.resolve();
 
    this._backgroundTasks = [];
    return Promise.all(tasks).then(() => {
      debug('finished %d background tasks', tasks.length);
    });
  },
 
  get _backgroundTasks() {
    if (!this[BACKGROUND_TASKS]) {
      this[BACKGROUND_TASKS] = [];
    }
    return this[BACKGROUND_TASKS];
  },
 
  set _backgroundTasks(tasks) {
    this[BACKGROUND_TASKS] = tasks;
  },
 
};
 
function findHeaders(headers, key) {
  if (!headers || !key) {
    return null;
  }
  key = key.toLowerCase();
  for (const headerKey in headers) {
    if (key === headerKey.toLowerCase()) {
      return headers[headerKey];
    }
  }
  return null;
}