DEV Community

Cover image for .toBe(true) or .toBeTruthy()
Majid Eltayeb
Majid Eltayeb

Posted on • Originally published at blog.majidz.com

.toBe(true) or .toBeTruthy()

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 exactly true.
  • 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
});
Enter fullscreen mode Exit fullscreen mode

.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 obviously true itself.
test('truthiness check', () => {
  const number = 1;
  const string = 'hello';
  expect(number).toBeTruthy(); // Passes
  expect(string).toBeTruthy(); // Passes
});
Enter fullscreen mode Exit fullscreen mode

That's it. Hope it's helpful.

Top comments (0)