@push.rocks/smartexpect

A testing library to manage expectations in code, offering both synchronous and asynchronous assertion methods.

readme.md for @push.rocks/smartexpect

Manage expectations in code with precise, readable assertions

Install

To install @push.rocks/smartexpect, use the following command in your terminal:

npm install @push.rocks/smartexpect --save

This will add @push.rocks/smartexpect to your project's dependencies. Make sure you're inside your project directory before running this command.

Why SmartExpect?

SmartExpect is designed to be a minimal, promise-first assertion library with clear, descriptive messaging and easy extensibility:

Usage

@push.rocks/smartexpect is a TypeScript library designed to manage expectations in your code effectively, improving testing readability and maintainability. Below are various scenarios showcasing how to use this library effectively across both synchronous and asynchronous code paths.

Getting Started

First, import @push.rocks/smartexpect into your TypeScript file:

import { expect } from '@push.rocks/smartexpect';

Synchronous Expectations

You can employ expect to create synchronous assertions:

import { expect } from '@push.rocks/smartexpect';

// Type assertions
expect('hello').toBeTypeofString();
expect(42).toBeTypeofNumber();
expect(true).toBeTypeofBoolean();
expect(() => {}).toBeTypeOf('function');
expect({}).toBeTypeOf('object');

// Negated assertions
expect(1).not.toBeTypeofString();
expect('string').not.toBeTypeofNumber();

// Equality assertion
expect('hithere').toEqual('hithere');

// Deep equality assertion
expect({ key: 'value' }).toEqual({ key: 'value' });

// Regular expression matching
expect('hithere').toMatch(/hi/);

Asynchronous Expectations

For asynchronous code, use the same expect function with the .resolves or .rejects modifier:

import { expect } from '@push.rocks/smartexpect';

const asyncStringFetcher = async (): Promise<string> => {
  return 'async string';
};

const asyncTest = async () => {
  // Add a timeout to prevent hanging tests
  await expect(asyncStringFetcher()).resolves.withTimeout(5000).type.toBeTypeofString();
  await expect(asyncStringFetcher()).resolves.toEqual('async string');
};

asyncTest();

Navigating Complex Objects

You can navigate complex objects using the property() and arrayItem() methods:

const complexObject = {
  users: [
    { id: 1, name: 'Alice', permissions: { admin: true } },
    { id: 2, name: 'Bob', permissions: { admin: false } }
  ]
};

// Navigate to a nested property
expect(complexObject)
  .property('users')
  .arrayItem(0)
  .property('name')
  .toEqual('Alice');

// Check nested permission
expect(complexObject)
  .property('users')
  .arrayItem(0)
  .property('permissions')
  .property('admin')
  .toBeTrue();

Advanced Assertions

Properties and Deep Properties

Assert the existence of properties and their values:

const testObject = { level1: { level2: 'value' } };

// Property existence
expect(testObject).toHaveProperty('level1');

// Property with specific value
expect(testObject).toHaveProperty('level1.level2', 'value');

// Deep Property existence
expect(testObject).toHaveDeepProperty(['level1', 'level2']);

Conditions and Comparisons

Perform more intricate assertions:

// Numeric comparisons
expect(5).toBeGreaterThan(3);
expect(3).toBeLessThan(5);
expect(5).toBeGreaterThanOrEqual(5);
expect(5).toBeLessThanOrEqual(5);
expect(0.1 + 0.2).toBeCloseTo(0.3, 10); // Floating point comparison with precision

// Truthiness checks
expect(true).toBeTrue();
expect(false).toBeFalse();
expect('non-empty').toBeTruthy();
expect(0).toBeFalsy();

// Null/Undefined checks
expect(null).toBeNull();
expect(undefined).toBeUndefined();
expect(null).toBeNullOrUndefined();

// Custom conditions
expect(7).customAssertion(value => value % 2 === 1, 'Value is not odd');

Arrays and Collections

Work seamlessly with arrays and collections:

const testArray = [1, 2, 3];

// Array checks
expect(testArray).toBeArray();
expect(testArray).toHaveLength(3);
expect(testArray).toContain(2);
expect(testArray).toContainAll([1, 3]);
expect(testArray).toExclude(4);
expect([]).toBeEmptyArray();
expect(testArray).toHaveLengthGreaterThan(2);
expect(testArray).toHaveLengthLessThan(4);

// Deep equality in arrays
expect([{ id: 1 }, { id: 2 }]).toContainEqual({ id: 1 });

Strings

String-specific checks:

expect('hello world').toStartWith('hello');
expect('hello world').toEndWith('world');
expect('hello world').toInclude('lo wo');
expect('options').toBeOneOf(['choices', 'options', 'alternatives']);

Functions and Exceptions

Test function behavior and exceptions:

const throwingFn = () => { throw new Error('test error'); };
expect(throwingFn).toThrow();
expect(throwingFn).toThrow(Error);

const safeFn = () => 'result';
expect(safeFn).not.toThrow();

Date Assertions

Work with dates:

const now = new Date();
const past = new Date(Date.now() - 10000);
const future = new Date(Date.now() + 10000);

expect(now).toBeDate();
expect(now).toBeAfterDate(past);
expect(now).toBeBeforeDate(future);

Debugging Assertions

The log() method is useful for debugging complex assertions:

expect(complexObject)
  .property('users')
  .log() // Logs the current value in the assertion chain
  .arrayItem(0)
  .log() // Logs the first user
  .property('permissions')
  .log() // Logs the permissions object
  .property('admin')
  .toBeTrue();

Customizing Error Messages

You can provide custom error messages for more meaningful test failures:

expect(user.age)
  .setFailMessage('User age must be at least 18 for adult content')
  .toBeGreaterThanOrEqual(18);

Custom Matchers

You can define your own matchers via expect.extend():

expect.extend({
  toBeOdd(received: number) {
    const pass = received % 2 === 1;
    return {
      pass,
      message: () =>
        `Expected ${received} ${pass ? 'not ' : ''}to be odd`,
    };
  },
});

// Then use your custom matcher in tests:
expect(3).toBeOdd();
expect(4).not.toBeOdd();

Full Matcher Reference

Below is a comprehensive list of all matchers and utility functions available in @push.rocks/smartexpect.

Modifiers and Utilities

Basic Matchers

Number Matchers

String Matchers

Array Matchers

Object Matchers

Function Matchers

Date Matchers

Type Matchers

Best Practices

This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the license file within this repository.

Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.

Trademarks

This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.

Company Information

Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany

By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

changelog.md for @push.rocks/smartexpect

2025-05-23 - 2.5.0 - feat(Assertion)

Add missing alias methods for length and emptiness checks and update documentation

2025-05-01 - 2.4.2 - fix(cleanup)

Remove unused scratch files

2025-04-30 - 2.4.1 - fix(Assertion)

Improve toHaveProperty alias by forwarding arguments correctly for intuitive object property assertions

2025-04-30 - 2.4.0 - feat(object)

add toHaveOwnProperty method and improve property-path matching in object assertions

2025-04-30 - 2.3.3 - fix(tests)

Fix test file naming inconsistencies

2025-04-30 - 2.3.2 - fix(object)

Update toHaveProperty matcher to support nested property paths using dot notation

2025-04-30 - 2.3.1 - fix(readme)

Improve README documentation with detailed 'Why SmartExpect' benefits section

2025-04-30 - 2.3.1 - fix(readme)

Improve README documentation with detailed 'Why SmartExpect' benefits section

2025-04-30 - 2.3.0 - feat(object-matchers)

Add object key matchers: toHaveKeys and toHaveOwnKeys; remove obsolete roadmap plan file

2025-04-29 - 2.2.2 - fix(license-files)

Remove legacy license file and add license.md to update file naming.

2025-04-29 - 2.2.1 - fix(readme)

Update usage examples and full matcher reference in README

2025-04-29 - 2.2.0 - feat(generics)

Improve assertion and matcher type definitions by adding execution mode generics for better async/sync support

2025-04-29 - 2.1.2 - fix(ts/index.ts)

Remove deprecated expectAsync function and advise using .resolves/.rejects on expect for async assertions

2025-04-29 - 2.1.1 - fix(Assertion)

Improve chainability by fixing return types in assertion methods

2025-04-28 - 2.1.0 - feat(core)

Add new matchers and improve negation messaging

2025-04-28 - 2.0.1 - fix(assertion-matchers)

Refactor matcher implementations to consistently use customAssertion for improved consistency and clarity.

2025-04-28 - 2.0.0 - BREAKING CHANGE(docs)

Update documentation and examples to unify async and sync assertions, add custom matcher guides, and update package configuration

2025-03-04 - 1.6.1 - fix(build)

Corrected package.json and workflow dependencies and resolved formatting issues in tests.

2025-03-04 - 1.6.0 - feat(assertion)

Enhanced the assertion error messaging and added new test cases.

2025-03-04 - 1.5.0 - feat(Assertion)

Add toBeTypeOf assertion method

2024-12-30 - 1.4.0 - feat(Assertion)

Add log method to Assertion class

2024-12-30 - 1.3.0 - feat(Assertion)

Refactor Assertion class for better error handling and code clarity

2024-08-24 - 1.2.1 - fix(Assertion)

Refactor methods for setting failure and success messages

2024-08-24 - 1.2.0 - feat(assertions)

Add custom fail and success messages for assertions

2024-08-17 - 1.1.0 - feat(assertion)

Add toBeDefined assertion method

2024-05-29 - 1.0.21 - General Updates

General updates and maintenance.

2023-08-12 - 1.0.20 to 1.0.21 - General Fixes

General fixes and update.

2023-07-10 - 1.0.15 - Organization Update

2023-06-22 - 1.0.14 to 1.0.19 - General Updates

General fixes and updates.

2022-02-02 - 1.0.8 to 1.0.13 - General Fixes

General fixes and update.

2022-01-20 - 1.0.1 to 1.0.7 - Initial Releases

Initial core updates and fixes.