DEV Community

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

Posted on β€’ Originally published at blog.majidz.com

2

.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.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay