should.js BDD Assertions

13.2.3 · active · verified Tue Apr 21

should.js is an expressive, BDD-style assertion library for JavaScript, designed to be framework-agnostic and provide helpful error messages. It is currently at version 13.2.3 and maintains an active release schedule with frequent patch and minor updates. A key differentiator is its default behavior of extending `Object.prototype` with a non-enumerable `should` getter, enabling `(value).should.be.something` syntax. For environments where `Object.prototype` extension is undesirable, it offers an alternative function-style API, `should(value).be.something`. The library ships with TypeScript type definitions, though specific import patterns have seen minor adjustments across versions. It aims for readability and clear test code.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates both the default `Object.prototype` extended assertion style and the explicit function-style `should()` API for various data types and asynchronous operations.

import 'should'; // Or `const should = require('should');` for CommonJS to get global assertions

// Using the Object.prototype extension (default behavior)
const user = {
    name: 'Alice',
    age: 30,
    isActive: true,
    tags: ['developer', 'tester']
};

user.should.have.property('name', 'Alice');
user.age.should.be.a.Number().and.be.exactly(30);
user.tags.should.have.lengthOf(2).and.containEql('developer');
user.isActive.should.be.true();

// Using the function-style API (without Object.prototype modification)
import shouldAsFunction from 'should/as-function'; // Or `const shouldAsFunction = require('should/as-function');`

shouldAsFunction(null).not.be.ok();
shouldAsFunction(undefined).not.exist();
shouldAsFunction(user.name).be.exactly('Alice');

// Example for async assertions (assuming a promise-returning function)
async function fetchData(id: number): Promise<any> {
    if (id === 1) return { id: 1, value: 'data' };
    throw new Error('Not found');
}

(async () => {
    try {
        const result = await fetchData(1);
        shouldAsFunction(result).be.an.Object().and.have.property('value', 'data');
    } catch (err: any) {
        shouldAsFunction(err).not.exist(); // This path should not be taken
    }

    try {
        await fetchData(2);
    } catch (err: any) {
        shouldAsFunction(err).be.an.Error().and.have.property('message', 'Not found');
    }
})();

view raw JSON →