weed weed - 7 months ago 9
Javascript Question

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

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.

Answer

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 }
Comments