Reputation: 2783
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.
Upvotes: 24
Views: 22042
Reputation: 395
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);
});
Upvotes: 2
Reputation: 479
Jasmine allows you to write your own "matchers". The documentation explains it. http://jasmine.github.io/2.0/custom_matcher.html
You could write a very specific matcher that is called
expect(obj).toHaveMethod("methodName");
Personally I would write something a bit more generic which checks the value type. That way I could use it to not just check if a method is defined on and object/instance, but anything that can store a value. It also gives me the possibility to check for types other then the function type.
expect(obj.methodName).toBeA(Function);
To get it to work you do have to make sure to add the toBeA "matcher".
beforeEach(function(){
jasmine.addMatchers({
toBeA: toBeA
});
});
function toBeA() {
return {
compare: function (value, type) {
var result = {pass: val != null && val.constructor === type || val instanceof type};
if (result.pass) {
result.message = 'Expected ' + value + ' to be a ' + type.name
} else {
result.message = 'Expected ' + value + ' to not be a ' + type.name
}
return result;
}
};
}
Upvotes: 0
Reputation: 89
I tried this solution and it works :
spyOn(@xhr,"open")
If there is not function open, it would throw Error because it can't start spyig on it
Upvotes: -1
Reputation: 10084
@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
Upvotes: 31
Reputation: 11134
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 }
Upvotes: 26