Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 598
Feel Physics Avatar asked Mar 28 '13 07:03

Feel Physics


People also ask

What is done () in Jasmine?

Using the done() Method in Your Jasmine-driven Asynchronous JavaScript Tests. Jasmine. Async is an add-on library for Jasmine that provides additional functionality to do asynchronous testing. Modeled after Mocha's async test support, it brings the done() function to the Jasmine unit testing environment.

How do you know if Jasmine is undefined?

ToBeUndefined() This matcher helps to check whether any variable is previously undefined or not, basically it works simply opposite to the previous matcher that is toBeDefined. In the following example, we will learn how to use this matcher.

Which function in Jasmine executes a function before each test?

JasmineJS - beforeEach() Another notable feature of Jasmine is before and after each function. Using these two functionalities, we can execute some pieces of code before and after execution of each spec.


2 Answers

@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

like image 179
Sukima Avatar answered Oct 24 '22 23:10

Sukima


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 } 
like image 31
HoLyVieR Avatar answered Oct 24 '22 22:10

HoLyVieR