Chai: Assertions for Readable JavaScript Tests
Chai makes your JavaScript tests read like sentences. It provides assertion styles like `expect(value).to.equal(5)` to verify code behavior in test frameworks like Mocha. The main footgun: the `should` style fails silently on null or undefined values.
WHY IT EXISTS Test runners like Mocha or Jest know how to run tests and report outcomes, but they don't provide the tools to check if a value is correct. You need a separate library to make these checks, or assertions. Chai provides a readable, human-friendly language to define what "correct" means for your code, replacing messy manual if/throw logic.
THE MENTAL MODEL Think of Chai as a fluent translator for your tests. It translates your expectations about your code's behavior into clear statements that either pass or fail with a helpful message. It offers different "dialects" for these statements—expect, should, and assert—so you can pick the one that feels most natural.
HOW IT WORKS Chai offers three core assertion styles. The BDD (Behavior-Driven Development) styles are chainable and read like English. The expect style uses a function wrapper: expect(user.name).to.equal('Ada'). The should style extends every object's prototype: user.name.should.equal('Ada'). In contrast, the TDD (Test-Driven Development) assert style is a classic, non-chainable approach with static methods: assert.equal(user.name, 'Ada'). You choose one style for your project and pair it with a test runner.
WHEN TO USE IT Use Chai in any JavaScript project—backend or frontend—where you are writing automated tests. Since it's framework-agnostic, it pairs well with runners like Mocha, Karma, or Jasmine. Its expressive BDD styles are particularly useful for making tests self-documenting, where the test code itself clearly describes the expected behavior of the system.
WHEN NOT TO USE IT Avoid adding Chai if your testing framework already includes a built-in assertion library you are happy with. For example, Jest comes with its own powerful expect implementation that is very similar to Chai's. Also, the should style is often avoided in modern projects because it modifies a global prototype and fails silently on null and undefined variables, which can lead to tests that pass incorrectly.
ONE CANONICAL EXAMPLE A test for a function that adds two numbers shows Chai's clarity. Using the expect style, you would write a test case that calls your function, add(2, 3), and then asserts the result. The assertion itself reads like a sentence: expect(result).to.equal(5). This is far more descriptive and provides better failure messages than a manual check like if (result !== 5) throw new Error(). The test clearly states its intent: it expects the result of adding 2 and 3 to equal 5.
Read the original → chaijs.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.