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
'use strict';
 
module.exports = app => {
  const customLoader = app.config.customLoader;
  if (!customLoader) return;
 
  for (const field of Object.keys(customLoader)) {
    const loaderConfig = Object.assign({}, customLoader[field]);
    loaderConfig.field = field;
    addMethod(loaderConfig);
  }
 
  function addMethod(loaderConfig) {
    const field = loaderConfig.field;
    const appMethodName = 'mock' + field.replace(/^[a-z]/i, s => s.toUpperCase());
    if (app[appMethodName]) {
      app.coreLogger.warn('Can\'t override app.%s', appMethodName);
      return;
    }
    app[appMethodName] = function(service, methodName, fn) {
      if (typeof service === 'string') {
        const arr = service.split('.');
        service = loaderConfig.inject === 'ctx' ? this[field + 'Classes'] : this[field];
        for (const key of arr) {
          service = service[key];
        }
        service = service.prototype || service;
      }
      this._mockFn(service, methodName, fn);
      return this;
    };
  }
};