Ricardo Rocha
Ricardo Rocha

Reputation: 16236

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

I noticed that if I write the expect expect(null).toBeDefined();, the test will be pass because Jasmine considers that null is an object defined but without any value.

My question is if there is a matcher that evaluates whether the object is different from both undefined and null.

Upvotes: 8

Views: 17262

Answers (6)

Syimyk Amatov
Syimyk Amatov

Reputation: 111

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

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

Example:

  fit(`jasmine.anything()`, () => {
    const undef = undefined;
    const nul = null;
    const foo = 'bar';
    const zero = 0;
    const nonZero = 1;

    expect(undef).toEqual(jasmine.anything()); // fail
    expect(nul).toEqual(jasmine.anything()); // fail
    expect(foo).toEqual(jasmine.anything()); // pass
    expect(zero).toEqual(jasmine.anything()); // pass
    expect(nonZero).toEqual(jasmine.anything()); // pass

    expect(undef).not.toEqual(jasmine.anything()); // pass
    expect(nul).not.toEqual(jasmine.anything()); // pass
    expect(foo).not.toEqual(jasmine.anything()); // fail
    expect(zero).not.toEqual(jasmine.anything()); // fail
    expect(nonZero).not.toEqual(jasmine.anything()); // fail
  });

Upvotes: 6

NotX
NotX

Reputation: 2365

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

Upvotes: 0

Terry Tú Nguyễn
Terry Tú Nguyễn

Reputation: 380

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

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

Upvotes: 0

Eric
Eric

Reputation: 343

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! :-)

Upvotes: 0

Duncan
Duncan

Reputation: 95652

Just use .toEqual():

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

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

Upvotes: 4

Ricardo Rocha
Ricardo Rocha

Reputation: 16236

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.

Upvotes: 1

Related Questions