Does Jasmine have an after-advice spy?

58 Views Asked by At

When spying on a method, we can either callThrough (use original implementation) or callFake (use a custom implementation).

What I want is a behaviour similar to callThrough but inspect/modify its return value before returning it to the caller.

So I can do something like this:

spyOn(foo, "fetch").and.afterCall(function(result) {
    expect(result).toBeDefined();
    result.bar = "baz";
    return result;
});

Right now the simplest way is doing something like this:

var original = foo.fetch;
foo.fetch = function() {
    var result = original.apply(this, arguments);
    expect(result).toBeDefined();
    result.bar = "baz";
    return result;
}

Which is somewhat annoying because now I have to manually restore the spy instead of having the framework automatically does it for me.

1

There are 1 best solutions below

0
On

Does Jasmine have an after-advice spy?

Generally: no.

You could extend the SpyStrategy object with such a function though:

this.callThroughAndModify = function(resultModifier) {
  var result;

  plan = function() {
    result = originalFn.apply(this, arguments);
    return resultModifier(result);
  };

  return getSpy();
};

You've to clone the above SpyStrategy file and insert that method.

Usage:

var obj = {
    fn: function(a) { return a * 2; }
};

spyOn(obj, "fn").and.callThroughAndModify(function(result) {
    console.log("Original result: ", result);
    return 1;
});

expect(obj.fn(2)).toBe(1);

Drawbacks: