Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine toBeUndefined

I'm new to Jasmine and assumed using the .not.toBeDefined() or .toBeUndefined() matches you could check if a variable is undefined:

describe('toBeDefined', function() {      it('should be defined', function() {         var obj = {};         expect(obj).toBeDefined(); // Passes     });      it('should not be defined using .not.tobeDefined()', function() {         //var obj = {};         expect(obj).not.toBeDefined(); // Fails // ReferenceError: obj is not defined     });      it('should not be defined using .tobeUnefined()', function() {         //var obj = {};         expect(obj).toBeUndefined(); // Fails // ReferenceError: obj is not defined     });  }); 

I completely get that this would fail within the code, but I assumed using those matches, it wouldn't. Am I just using these wrong, or is it not possible to write a spec to check if something is undefined?

like image 200
Tom Doe Avatar asked Feb 03 '13 18:02

Tom Doe


People also ask

What is ToBedefined in Jasmine?

ToBedefined() This matcher is used to check whether any variable in the code is predefined or not.

How do you check if a function is called in Jasmine?

We can use the toHaveBeenCalled matcher to check if the function is called. Also, we can use toHaveBeenCalledTimes to check how many times it's been called. The toHaveBeenCalledWith method lets us check what parameters have the functions been called when they're called.

Which matter is used in jasmine to check whether the result is equal to true or false?

Perhaps the simplest matcher in Jasmine is toEqual . It simply checks if two things are equal (and not necessarily the same exact object, as you'll see in Chapter 5).

Which matcher function is tested greater than condition?

You can use the function least to check if a value is greater than or equal to some other value. An alias of least is gte (great than or equal to).


1 Answers

The problem is that

  expect(obj).toBeUndefined(); 

fails before the call to Jasmine even happens. It's erroneous to refer to a variable that's not defined (in new browsers or in "strict" mode at least).

Try this setup instead:

it('should not be defined using .tobeUnefined()', function() {     var obj = {};     expect(obj.not_defined).toBeUndefined();  }); 

In that code, there's a variable "obj" whose value is an empty object. It's OK in JavaScript to refer to a non-existent property of an object, and because such a reference results in undefined the test will pass. Another way to do it would be:

it('should not be defined using .tobeUnefined()', function() {   var no_value;    expect(no_value).toBeUndefined(); }); 
like image 157
Pointy Avatar answered Sep 29 '22 21:09

Pointy