toBeTruthy() will bite you — use toBe(true)
September 22, 2016
(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
toBeFalse(). But they're not: truthy and falsy refer to values that are evaluated to
false after being coerced to a boolean!
true is truthy, but
42 is also truthy, and even
'false' are truthy! In fact, everything that is not
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
So then what should I use?
Just use the plain old
toBe() matcher to check for a value
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.