promisify automock socketio | | Create an RPC socker.io server for any module using promisify | Search

This code defines a function promisifyMock that creates mock implementations for asynchronous functions in a request object, enabling easier testing by replacing these functions with controlled stubs.

Run example

npm run import -- "mock and pass through"

mock and pass through

var Promise = require('bluebird');
var importer = require('../Core');
var automock = importer.import("mock all properties and functions using rewire");

function promisifyMock(req, dep) {
    let ctx;
    ctx = automock.mockValue(req, {
        stubCreator: (name) => {
            var orig = Promise.promisify(req[name.split('.')[1]], {
                multiArgs: true,
                context: req
            });
            //console.log('create stub ' + name);
            return function () {
                console.log(name + ' (' + arguments[0] + ') in ' + JSON.stringify(dep));
                return orig.apply(null, arguments);
            };
        }
    });
    return ctx;
};
module.exports = promisifyMock;

What the code could have been:

const Bluebird = require('bluebird');
const importer = require('../Core');
const rewire = require('rewire'); // Import rewire directly for clarity

/**
 * Creates a promisified mock for the given request and dependency.
 *
 * @param {Object} req - The object to be mocked.
 * @param {Object} dep - The dependency object.
 * @returns {Object} - The promisified mock object.
 */
async function promisifyMock(req, dep) {
  const automock = rewire('../Core').import('mock all properties and functions using rewire');
  const ctx = await automock.mockValue(req, {
    stubCreator: (name) => {
      // Extract the method name from the property name (e.g., 'prop.method')
      const methodName = name.split('.').pop();
      const origMethod = Bluebird.promisify(req[methodName], {
        multiArgs: true,
        context: req
      });

      // Return a function that logs the method call and its arguments, then calls the original method
      return async function (...args) {
        console.log(`${name} (${JSON.stringify(args)}) in ${JSON.stringify(dep)}`);
        return origMethod.apply(null, args);
      };
    }
  });

  return ctx;
}

module.exports = promisifyMock;

This code defines a function promisifyMock that creates mock implementations for asynchronous functions within a given request object (req) using the rewire library.

Here's a breakdown:

  1. Dependencies:

  2. promisifyMock Function:

  3. Export:

In essence, this code provides a way to mock asynchronous functions within a request object, allowing for easier testing and mocking of dependencies.