Skip to content

Intercept function calls to modify/change arguments or results, or run some intermediary functionality when called.

Notifications You must be signed in to change notification settings

calvinwiebe/fn-intercept

Repository files navigation

Build Status Coverage Status

fn-intercept

Similar to what sinon.js does to stub functions, but in a compact and super tiny library. Useful for debug mode in browsers where size is important, or where you want to use function intercepting outside of testing.

What these functions will do is take an original function, wrap it with another that will call a function you provide with a reference to the original, and all of the arguments that the original was called with. It will return the wrapped function reference to call as if it were the original.

In the syncObject/asyncObject cases, it will take an object instance, and a function name. It will replace the function reference on the object with a new wrapped function. You can later put the original function back by calling obj[fnName].restore().

Usage

// example of a simple sync function

var intercept = require('fn-intercept').sync;

var foo = function(x, y) {
  return x * y;
}

// `fn` here is the reference to `foo`.
var wrapped = intercept(foo, function(fn, x, y) {
  var result = fn(x*2, y*2);
  return 'The answer is ' + result;
});

console.log(wrapped(1, 2));

// This will output 'The answer is 6'

console.log(foo(1, 2));

// This will output 3

The same can be done for async functions, and functions that are members of an object. Please see the tests for a bunch of examples.

Promises

Nothing special needs to be done to support promises. You can simply use the sync functions. Since you get a reference to the original function, you can call the function, intercept its .then, and do whatever you want.

Example

var sync = require('fn-intercept').sync;

var foo = function(x, y) {
  return Promise.resolve(x + y);
}
var wrapped = sync(foo, function(fn, x, y) {
  return Promise.resolve()
  .then(function() {
    return fn(x, y);
  })
  .then(function(result) {
    return result * 2;
  });
});

wrapped(1, 1).then(function(result) {
  console.log(result);
});

// should output 4

API

sync(original, intercept)

Wrap a synchronous function. examples

syncObject(obj, fnName, intercept)

Wrap a synchronous member function of an object. examples

async(original, options, intercept, cbIntercept)

Wrap an asynchronous function. examples

asyncObject(obj, fnName, options, intercept, cbIntercept)

Wrap an asynchronous member function of an object. examples

About

Intercept function calls to modify/change arguments or results, or run some intermediary functionality when called.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published