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
?
ToBedefined() This matcher is used to check whether any variable in the code is predefined or not.
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.
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).
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).
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(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With