简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM