tmatch Deep Object Matching

5.0.0 · active · verified Wed Apr 22

tmatch is a utility module designed to facilitate deep and flexible object matching, primarily used by the `t.match()` method in the `tap` test framework. Currently at version 5.0.0, it provides a comprehensive algorithm for comparing a target value against a pattern, supporting various data types including objects, arrays, regular expressions, dates, buffers, and constructor functions. Its matching logic goes beyond shallow equality, handling nested structures and specific type-based comparisons. For instance, it can match strings against regular expressions, check if an object is an `instanceof` a given constructor, or assert the absence of a property using `{propertyName: null}`. While its release cadence is tied to `tap`, it is generally stable. Key differentiators include its detailed, multi-step matching algorithm that accounts for many edge cases and its utility in robust assertion scenarios, offering a more nuanced comparison than standard deep equality checks.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates `tmatch` for deep object comparison, including regex matching and asserting property absence with `null`.

const tmatch = require('tmatch');

// Simulate an HTTP response object
const mockResponse = {
  statusCode: 200,
  headers: {
    'content-type': 'application/json',
    server: 'express/4.17.1'
  },
  body: {
    message: 'Hello, world!'
  }
};

const expectedPattern = {
  statusCode: 200,
  headers: {
    server: /express/, // Matches any server header containing 'express'
    'content-type': 'application/json' // Exact string match
  },
  // 'body' property is not in pattern, so it's ignored during matching
};

if (tmatch(mockResponse, expectedPattern)) {
  console.log('Response matches the expected pattern!');
} else {
  console.error('Response DOES NOT match the expected pattern.');
  console.error('Actual:', JSON.stringify(mockResponse, null, 2));
  console.error('Pattern:', JSON.stringify(expectedPattern, null, 2));
}

// Example of asserting a property's absence using null
const negativePattern = {
  headers: {
    'x-powered-by': null // Ensures 'x-powered-by' property is absent
  }
};

const responseWithXPoweredBy = {
  statusCode: 200,
  headers: {
    'x-powered-by': 'Express',
    server: 'express/4.17.1'
  }
};

if (!tmatch(responseWithXPoweredBy, negativePattern)) {
  console.log("Response does not have 'x-powered-by' header as expected (correct behavior for negative pattern).");
} else {
  console.error("Response HAS 'x-powered-by' header, but pattern expected it absent.");
}

view raw JSON →