or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

assertion-modifiers.mdcontent-testing.mdcore-functions.mdfunction-testing.mdindex.mdnumeric-comparisons.mdpattern-validation.mdpromise-testing.mdsettings.mdstring-assertions.mdtype-assertions.mdvalue-assertions.md
tile.json

index.mddocs/

@hapi/code

@hapi/code is a lightweight BDD assertion library designed for Node.js testing. Created as a rewrite of chai, it provides a fluent, chainable API for test assertions with improved safety by avoiding property/method mixing that can lead to unexecuted assertions.

Package Information

  • Package Name: @hapi/code
  • Package Type: npm
  • Language: JavaScript with TypeScript definitions
  • Installation:
    npm install @hapi/code
  • Dependencies: @hapi/hoek (9.x.x)

Core Imports

const Code = require('@hapi/code');
const expect = Code.expect;

For ES modules:

import * as Code from '@hapi/code';
const { expect } = Code;

Basic Usage

const Code = require('@hapi/code');
const expect = Code.expect;

// Basic assertions
expect(true).to.be.a.boolean().and.to.not.equal(false);
expect(10).to.be.above(5);
expect('hello world').to.be.a.string().and.contain('world');
expect([1, 2, 3]).to.be.an.array().and.have.length(3);

// Error handling
expect(() => {
    throw new Error('Something went wrong');
}).to.throw(Error, /wrong/);

// Promise rejection testing
await expect(Promise.reject(new Error('Failed'))).to.reject();

Architecture

@hapi/code is built around several key components:

  • Assertion Chain: Fluent interface using
    expect()
    that returns chainable assertion objects
  • Grammar System: Natural language words (
    to
    ,
    be
    ,
    have
    , etc.) for readable assertions
  • Flag System: Behavior modifiers (
    not
    ,
    shallow
    ,
    once
    ,
    only
    ,
    part
    ) that toggle assertion behavior
  • Type Detection: Built-in type checking for JavaScript primitives and objects
  • Integration Features: Assertion counting and incomplete assertion tracking for test runners
  • Error Reporting: Detailed error messages with source location information

Capabilities

Core Assertion Functions

Essential functions for creating assertions, controlling test flow, and integrating with test runners.

function expect(value, prefix) {
    // Creates assertion chain for value with optional error message prefix
    // Returns: Assertion object with chainable methods
}

function fail(message) {
    // Makes test fail immediately with provided message
    // Throws: Error with message
}

function count() {
    // Returns total number of assertions created
    // Returns: number
}

function incomplete() {
    // Returns locations of incomplete assertions  
    // Returns: string[] | null
}

function thrownAt(error) {
    // Returns location where error was thrown
    // Returns: Location object {filename, line, column}
}

Core Functions

Type Assertions

Comprehensive type checking for JavaScript primitives, built-in objects, and custom types.

// Type assertion methods available on assertion chains
arguments()    // Asserts value is arguments object
array()        // Asserts value is Array
boolean()      // Asserts value is boolean
buffer()       // Asserts value is Buffer  
date()         // Asserts value is Date
error(type?, message?)  // Asserts value is error with optional constraints
function()     // Asserts value is function
number()       // Asserts value is number
regexp()       // Asserts value is RegExp
string()       // Asserts value is string
object()       // Asserts value is object (excluding arrays, etc.)

Type Assertions

Value Assertions

Precise value checking for specific JavaScript values and special numeric values.

// Value assertion methods
true()         // Asserts value is true
false()        // Asserts value is false  
null()         // Asserts value is null
undefined()    // Asserts value is undefined
NaN()          // Asserts value is NaN

Value Assertions

Content and Relationship Testing

Advanced assertions for strings, arrays, and objects including inclusion, existence, and size checks.

include(values)    // Asserts inclusion of values (strings, arrays, objects)
exist()           // Asserts value is not null/undefined
empty()           // Asserts value has length 0 or no keys
length(size)      // Asserts value has specific length/key count
equal(value, options?)  // Deep equality comparison with options

Content Testing

String-Specific Assertions

Specialized string operations for prefix/suffix checking.

startWith(value)   // Asserts string starts with value (alias: startsWith)
endWith(value)     // Asserts string ends with value (alias: endsWith)

String Assertions

Numeric Comparisons

Mathematical comparison operations for numbers and numeric values.

above(value)       // Greater than (alias: greaterThan)
least(value)       // Greater than or equal (alias: min)
below(value)       // Less than (alias: lessThan)  
most(value)        // Less than or equal (alias: max)
within(from, to)   // Inclusive range check (alias: range)
between(from, to)  // Exclusive range check
about(value, delta) // Approximate equality within delta

Numeric Comparisons

Pattern and Custom Validation

Advanced validation using regular expressions, type checking, and custom validator functions.

instanceof(type)    // Instance type checking (alias: instanceOf)
match(regex)        // Regex pattern matching (alias: matches)
satisfy(validator)  // Custom validation function (alias: satisfies)

Pattern Validation

Function Testing

Specialized assertions for testing function behavior, including exception throwing.

throw(type?, message?)   // Asserts function throws exception (alias: throws)
// Returns the thrown error object for further inspection

Function Testing

Promise Testing

Asynchronous testing capabilities for Promise rejection scenarios.

reject(type?, message?)  // Asserts Promise rejects with exception (alias: rejects)
// Returns Promise resolving to rejected error object

Promise Testing

Assertion Modifiers

Behavior modification system using flags and grammar words for readable, flexible assertions.

// Grammar words (no functional impact, for readability)
a, an, and, at, be, have, in, to

// Behavior flags
not           // Inverts assertion result
once          // Requires single occurrence (for include)
only          // Requires exact match (for include) 
part          // Allows partial matching (for include)
shallow       // Use strict equality instead of deep comparison

Assertion Modifiers

Settings and Configuration

const settings = {
    truncateMessages: false,    // Truncate long error messages
    comparePrototypes: false    // Include prototypes in deep comparisons
};

Settings