Jasmine toBeUndefined
Solution 1
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();
});
Solution 2
Note that your error says that obj is not defined
.
It does not say that obj is undefined.
undefined is actually a data type in Javascript.
Any declared variable without an assignment is given a value of undefined by default, but that variable must be declared.
So when Jasmine tests whether a value is undefined, it is determining if obj === undefined
.
If you declare
var obj;
then obj
will test as undefined.
If you do not declare obj
, then there is nothing for the Jasmine matcher to compare against the data type of undefined.
Tom Doe
Updated on October 14, 2022Comments
-
Tom Doe over 1 year
I'm new to Jasmine and assumed using the
.not.toBeDefined()
or.toBeUndefined()
matches you could check if a variable isundefined
: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
?