mercredi 29 avril 2015

How to write a test in Jasmine where the object's existence is checked prior to the function call on that object?

It's easiest to describe the problem by showing a code sample.

Code under test:

function something() {
    if(this.myObject) {
        this.myObject.callMyFunction();
    }

    this.callAnotherFunction();
}

Jasmine test:

it("should call myObject.callMyFunction() because 'myObject' is defined") {
    spyOn(theScope, "callAnotherFunction");
    theScope.something();
    expect(theScope.myObject.callMyFunction).toHaveBeenCalled(); // a spy has already been created for theScope.myObject.callMyFunction
} // TEST PASSES

it("should not call myObject.callMyFunction() because 'myObject' is undefined") {
    spyOn(theScope, "callAnotherFunction");
    theScope.myObject = undefined;
    theScope.something();
    expect(theScope.myObject.callMyFunction).not.toHaveBeenCalled(); // a spy has already been created for theScope.myObject.callMyFunction
} // TEST FAILS

As you can see in the second test, I'm trying to set theScope.myObject to be undefined, but the test won't run because it's then calling callMyFunction() on the undefined object theScope.myObject.

Aucun commentaire:

Enregistrer un commentaire