Bob Tway
Bob Tway

Reputation: 9613

Javascript unit testing - using Jasmine to spy on self-invoking function

With a javascript construct like this:

var myClass = function(myArgumentObject) {

    var vm = {
        myFunction: myFunction,
        myVariable: myVariable
    }
    return vm;

    myFunction() {
        myVariable = 1 + 1;
        myArgumentObject.aMethod();
    }

} (myArgumentObject);

How (if at all) can one use the Jasmine framework to spy on (i.e. mock out) myArgumentObject so that one can unit test myFunction?

Doing this:

it('test myFunction', function () {
    myClass.myFunction();
    expect(myClass.myVariable).toEqual(2);
});

Fails because there's an error when it tries to call a method on myArgumentObject. I know I can create a fake version of myArgumentObject with jasmine.createSpy but I can't see how you pass it in.

Upvotes: 2

Views: 3836

Answers (2)

ginna
ginna

Reputation: 1801

Great question! Testing is key.

You can define your arguments/input within your test:

it ('test myClass function', function() {
    myArgumentObject = function() {
        this.aMethod: jasmine.createSpy();
    };
    // mock out initial values for your other variables here, eg myVariable

    spyOn(vm, 'myFunction').andCallThrough();

    myClass(myArgumentObject)

    expect(myArgumentObject.aMethod).toHaveBeenCalled()
    expect(vm.myVariable).toEqual(2)
});

A couple things to keep in mind -- Your 'return vm' statement will cut your function off early -- you won't need it.

You should define your variables early so that you don't get an error. Consider moving myFunction above the 'vm' object.

Upvotes: 1

Andreas Köberle
Andreas Köberle

Reputation: 111062

So I assume the following, you have a global variable called myArgumentObject which have function aMethod. Then you can spy on this function using jasmine like this.

it('test myFunction', function () {
  spyOn(myArgumentObject, 'aMethod')
  myClass.myFunction();
  expect(myClass.myVariable).toEqual(2);
});

But if there is no gloabl variable you cant test this, cause then undefined is passed to the test and it will always fail, as you can't change private variables in the scope of the function.

Upvotes: 0

Related Questions