6

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.

Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
  • If it is an object, you can use `toBeFalsy`, since it won't compare it to 0, `''`, or NaN. For more information, see the [documentation about falsy values](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) –  Sep 11 '18 at 09:59

6 Answers6

5

Just use .toEqual():

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

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

Duncan
  • 92,073
  • 11
  • 122
  • 156
  • 1
    Error: Expected undefined to equal null. – Ali Adravi Oct 06 '20 at 19:06
  • @AliAdravi That's odd. I thought I had tested this at the time but Jasmine explicitly checks whether either value being compared is `null` and if so uses `===`. I would delete this answer but can't delete accepted posts. Thanks anyway. – Duncan Oct 07 '20 at 08:53
4

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

expect(context).toEqual(jasmine.anything());
Syimyk Amatov
  • 71
  • 1
  • 4
1

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.

Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
0

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! :-)
Dharman
  • 30,962
  • 25
  • 85
  • 135
Eric
  • 343
  • 4
  • 14
0

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

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

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

NotX
  • 1,516
  • 1
  • 14
  • 28