Search code examples
javascriptunit-testingbddjasmine

Trying to understand Jasmine's toHaveBeenCalled() matcher


I am new to jasmine here is my src file in which i create Auth class

function Auth() {
}

Auth.prototype.isEmpty = function(str) {
    return (!str || 0 === str.length);
}

Auth.prototype.Login = function (username , password) {
    if (this.isEmpty(username) || this.isEmpty(password)) {
        return "Username or Password cann't be blank ";
    }
    else {
        return "Logged In !";
    }
}

now i want to test jasmine's toHaveBeenCalled() matcher . Here is what i write

it("should be able to Login", function () {
    spyOn(authobj);
    expect(authobj.Login('abc', 'abc')).toHaveBeenCalled();
});

but it says that undefined() method does not exist


Solution

  • EDIT: Look at basecode answer for a better approach


    From the docs, you should use it like the following:

    spyOn(foo, 'setBar');
    
    it("tracks that the spy was called", function() {
      expect(foo.setBar).toHaveBeenCalled();
    });
    

    So you should write:

    it("should be able to Login", function () {
      spyOn(authobj, 'isEmpty');  
      authobj.Login('abc', 'abc');  
      expect(authobj.isEmpty).toHaveBeenCalled();
    });