I was reviewing a feature on GitHub and noticed my colleague sometimes used .toBe(true)
and other times .toBeTruthy()
. This got me wondering, are they actually different? After a quick search, I found out they are – and it's all in their names 😅. In this post, I'll break down these two functions and how they're not quite the same
.toBe(true)
- Strict Equality
-
.toBe(true)
is used to test strict equality. It checks if the value being tested is exactlytrue
. - This means that the test will only pass if the value is the Boolean primitive
true
. - It's similar to using
=== true
test('strict true check', () => {
const value = true;
expect(value).toBe(true); // Passes
});
.toBeTruthy()
- Truthiness Check
-
.toBeTruthy()
, on the other hand, tests for 'truthiness' rather than strict Boolean true. - A value is considered "truthy" if it translates to true when evaluated in a Boolean context.
- This includes values like
1
,'non-empty string'
,{}
,[]
, and obviouslytrue
itself.
test('truthiness check', () => {
const number = 1;
const string = 'hello';
expect(number).toBeTruthy(); // Passes
expect(string).toBeTruthy(); // Passes
});
That's it. Hope it's helpful.
Top comments (0)