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?
The problem is that
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:
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
undefinedthe test will pass. Another way to do it would be: