Here’s a short public service announcement for those who write their tests using Jasmine or Protractor: avoid the toBeTruthy() and toBeFalsy() matchers and use toBe(true) and toBe(false) instead.

(Off topic: I’ve also seen people confuse Jasmine and Karma. Karma fires up a browser to run tests in, but the actual tests are written using a testing library such as Jasmine.)

What’s the problem?

I’ve seen people using these matchers assuming they’re just a weird spelling of toBeTrue() and toBeFalse(). But they’re not: truthy and falsy refer to values that are evaluated to true and false after being coerced to a boolean!

So yes, true is truthy, but 42 is also truthy, and even [] and 'false' are truthy! In fact, everything that is not 0, "", null, undefined, NaN or false is truthy.

This means that if you’re testing a function that errorenously returns 'false' (a string) instead of false (a boolean), toBeTruthy() will match and toBeFalsy() will not.

So just like you should never use ==, try to avoid toBeTruthy() and toBeFalsy().

So then what should I use?

Just use the plain old toBe() matcher to check for a value toBe(true) or toBe(false), respectively. Unless you actually want your function to return different types of values, but even then I’d recommend you to change your code: otherwise, everywhere you’re calling that function, you have to check for all possible return types.


This work by Vincent Tunru is licensed under a Creative Commons Attribution 4.0 International License.