Chai Assertion Library
Chai is a widely used BDD/TDD assertion library for both Node.js and browser environments, designed to be framework-agnostic and pair delightedly with any JavaScript testing framework. The current stable version is 6.2.2, with frequent patch and minor releases, alongside periodic major updates, demonstrating an active development cadence.
Common errors
-
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'chai/lib/expect' imported from ...
cause Attempting to import internal `lib/*.js` files directly after Chai v6.0.0, which bundled the library into a single `index.js`.fixChange the import path to `import { expect } from 'chai';` or `import { assert } from 'chai';`. -
TypeError: (0 , chai__WEBPACK_IMPORTED_MODULE_0__.should) is not a function
cause Using Chai's `should` assertion style without calling `should()` after importing it, which is necessary to extend `Object.prototype`.fixAdd `should();` immediately after the import statement: `import { should } from 'chai'; should();`. -
ReferenceError: require is not defined
cause Attempting to use the CommonJS `require` function in an ECMAScript Module (ESM) file context (e.g., a `.mjs` file or a project with `"type": "module"` in `package.json`).fixUpdate your code to use ESM `import` statements, for example, `import { expect } from 'chai';` instead of `const expect = require('chai').expect;`.
Warnings
- breaking Chai v6.0.0 introduced a breaking change where direct imports from internal `lib/*.js` files are no longer supported. The library is now bundled into a single `index.js`.
- gotcha When using Chai's `should` assertion style, you must explicitly call `should()` after importing it to extend `Object.prototype` and enable the assertion syntax.
- gotcha Importing a Chai assertion style globally (e.g., `import 'chai/register-expect';`) modifies the global scope. While convenient for quick setups, this can lead to unexpected side effects or conflicts in larger projects.
Install
-
npm install chai -
yarn add chai -
pnpm add chai
Imports
- expect
const expect = require('chai').expect;import { expect } from 'chai'; - assert
const assert = require('chai').assert;import { assert } from 'chai'; - should
import { should } from 'chai';import { should } from 'chai'; should();
Quickstart
import { expect } from 'chai';
const add = (a, b) => a + b;
const isPositive = (num) => num > 0;
// Basic assertions
expect(add(2, 3)).to.equal(5);
expect(add(-1, 5)).to.be.above(0);
expect(isPositive(10)).to.be.true;
// Deep equality for objects
expect({ a: 1, b: 2 }).to.deep.equal({ a: 1, b: 2 });