Jasmine to test whether a object has a certain method or not

20,643

Solution 1

There isn't a built-in way to do it, but you can achieve the desired result by doing this.

it "should have 'open' method", ->
    @xhr = ajax.create()
    expect(typeof @xhr.open).toBe("function")

Do note that testing if it's defined as proposed in the other answer has some edge cases where it will pass and it shouldn't. If you take the following structure, it will pass and it's definitely not a function.

{ open : 1 }

Solution 2

@david answered it correctly. toBeDefined() is probably what you want. However if you want to verify that it is a function and not a property then you can use toEqual() with jasmine.any(Function). Here is an example: http://jsbin.com/eREYACe/1/edit

Solution 3

I would try:

it "should have 'open' method", ->
    @xhr = ajax.create()
    expect(@xhr.open).toBeDefined()

see this fiddle.

Solution 4

I did it like this. Angular example:

beforeEach(inject(function ($injector) {
    service = $injector.get("myService");       
}));

it("should have myfunction function", function () {
    expect(angular.isFunction(service.myfunction)).toBe(true);
});
Share:
20,643
Feel Physics
Author by

Feel Physics

I developed Physics education app using mixed reality, and gave experience sessions / lessons in five countries including Africa.

Updated on July 11, 2022

Comments

  • Feel Physics
    Feel Physics almost 2 years

    I am using Jasmine, and I want to test whether a object has a certain method or not, like below:

    it "should have 'open' method", ->
        @xhr = ajax.create()
        expect(@xhr).toHaveMethod "open" # I want to test like this!
    

    How can I test? Thanks for your kindness.