0

I'm using Jasmine to do unit tests and I am spying on a function:

it('should loop through all inputs', function() {
    var test = function() {};
    spyOn(this, 'test').andCallThrough();
    formManager.eachInputs($unfoldedView, test);
    expect(test).toHaveBeenCalled()
});

My problem is that the spyOn takes two parameters: (context, function). What is the context of the test function and how do I get it? It's context is the inside of this anonymous function, but I don't know how to get that. (I wrote this as the context parameter, but it's not that)

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

1 Answers1

1

When you're in the global scope, your declared variables exist as members on the global object (either window or global). When you declare variables in a local function scope, there is no analogous "local" object. (See the Stack Overflow question "JavaScript: Reference a functions local scope as an object" for more details.)

Instead, you can make your function a method of an object and use that object as the context:

it('should loop through all inputs', function() {
    var obj = { test: function() {} };
    spyOn(obj, 'test').andCallThrough();
    formManager.eachInputs($unfoldedView, obj.test);
    expect(obj.test).toHaveBeenCalled()
});
Community
  • 1
  • 1
apsillers
  • 112,806
  • 17
  • 235
  • 239