Should.js Type Adaptors

1.1.0 · maintenance · verified Sun Apr 19

The `should-type-adaptors` library (current stable version 1.1.0) provides low-level utility functions specifically designed to enhance the `should.js` BDD-style assertion library. Its core purpose is to enable consistent deep comparison, property traversal, and accurate type inspection across diverse JavaScript data structures, particularly those that might deviate from standard object or array behaviors. The library allows for the registration of custom type adaptors, facilitating intelligent handling of complex, custom, or "adapted" types during `should.js` assertions. Maintained as part of the `should.js` ecosystem, its latest updates were for dependency management, suggesting it is in a maintenance state rather than active development. Its key differentiator is offering an extensible mechanism for `should.js` to correctly interpret and assert against non-standard or complex type structures.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to register a custom type adaptor for a user-defined class (`MyCustomType`) with `should-type-adaptors`. It configures `should.js` to use a custom `valueOf` method for deep comparisons, enabling robust assertions on complex objects. This is typically how `should-type-adaptors` extends `should.js`'s capabilities.

import should from 'should';
import { addTypeAdaptor } from 'should-type-adaptors';

// Define a custom class
class MyCustomType {
  constructor(id, value) {
    this.customId = id;
    this.data = value;
  }

  // A method that might be important for comparison
  getFormattedData() {
    return `ID: ${this.customId}, Data: ${this.data}`;
  }
}

// Register a type adaptor for MyCustomType to define how 'should.js' should compare it
// This adaptor tells should.js to use 'getFormattedData' for deep comparisons.
addTypeAdaptor(MyCustomType, {
  valueOf: (instance) => instance.getFormattedData(),
  // You can also define custom 'eql' or 'inspect' methods here
  // eql: (a, b) => a.customId === b.customId && a.data === b.data,
  // inspect: (instance, level) => `MyCustomType { id: ${instance.customId}, data: '${instance.data}' }`
});

const instance1 = new MyCustomType(1, 'hello');
const instance2 = new MyCustomType(1, 'hello');
const instance3 = new MyCustomType(2, 'world');

// Now should.js can compare custom types based on their adapted value
should(instance1).eql(instance2); // This assertion will pass because valueOf makes them deeply equal
should(instance1).not.eql(instance3); // This assertion will pass

console.log('Assertions passed successfully!');

// Example of direct usage of convert (less common)
// import { convert } from 'should-type-adaptors';
// const convertedValue = convert(instance1); // Will be 'ID: 1, Data: hello'
// console.log(convertedValue);

view raw JSON →