Jasmine: Matcher to be different from undefined and diferent from null (!= undefined and != null)

Viewed 9730

I had notice that if I write the expect expect(null).toBeDefined();, the test will be passed, because the jasmine considers that null is a object difined but without any value.

My question is that if there is a matcher that evaluates if the object is diferent that undefined and null at the same time.

6 Answers

Fails if context is null or undefined. This better way for checking existing

expect(context).toEqual(jasmine.anything());

Just use .toEqual():

expect(context).not.toEqual(null);

In Javascript undefined == null is true, so this test will exclude both undefined and null.

The only way that I find out was to evaluate if is undefined and if is not null in diferent statements like follows:

expect(context).toBeDefined();
expect(context).not.toBeNull();

But this not really answer my question.

So as far as I understand you can use the juggling-check to check for both null and undefined.

let foo;
console.log(foo == null); // returns true when foo is undefined

let bar = null;
console.log (bar == null); // returns true when bar is null

Then I have been doing this with the jasmine expect

expect(foo == null).toBe(true);  // returns true when foo is null or undefined

It would be really great if we could do this (but you can't as far as I know).

expect(foo).toBeNullOrUndefined() // How cool would that be! :-)

This is my approach. I think it's descriptive.

 expect(![null, undefined].includes(myValue))
    .withContext('myValue should not be null or undefined')
    .toEqual(true);

I resorted to expect(myValue || undefined).toBeDefined(), so a possible null would become undefined which then fails the condition as desired.

Related