Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why expect component to be truthy instead of defined

This a a general question.

When scaffolding a component with the Angular-cli, it creates the first test itself.

It looks something like this:

it('should create', () => {
 expect(component).toBeTruthy();
});

How Come it checks if it's Truthy and not Defined? And what is the difference?

Thanks in advance :)

like image 948
methgaard Avatar asked Jun 16 '17 09:06

methgaard


1 Answers

The truthy source code:

getJasmineRequireObj().toBeTruthy = function() {

  function toBeTruthy() {
    return {
      compare: function(actual) {
        return {
          pass: !!actual
        };
      }
    };
  }

  return toBeTruthy;
};

The defined source code:

getJasmineRequireObj().toBeDefined = function() {
  function toBeDefined() {
    return {
      compare: function(actual) {
        return {
          pass: (void 0 !== actual)
        };
      }
    };
  }

https://github.com/jasmine/jasmine/blob/4097718b6682f643833f5435b63e4f590f22919f/lib/jasmine-core/jasmine.js#L2908

So it's a comparison between !!actual and void 0 !== actual.

void 0 is same as undefined AFAIK and to me although they are practically the same, toBeDefined is a more secure way to check for defined values on some edge cases.

For example:

expect(0).toBeTruthy() will evaluate to false/fail

expect(0).toBeDefined() will evaluate to true/success

There are more of these cases as @trichetriche mentioned in the comments.

However for your case, it won't make a difference.

like image 142
eko Avatar answered Nov 04 '22 15:11

eko