1.0.0 • Public • Published


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().


// 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.


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.


var sync = require('fn-intercept').sync;
var foo = function(x, y) {
  return Promise.resolve(+ 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) {
// should output 4


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

Package Sidebar


npm i fn-intercept

Weekly Downloads






Last publish


  • calvinwiebe