A testing library to manage expectations in code, offering both synchronous and asynchronous assertion methods.
To install @push.rocks/smartexpect, use the following command in your terminal:
``bash`
npm install @push.rocks/smartexpect --save@push.rocks/smartexpect
This will add to your project's dependencies. Make sure you're inside your project directory before running this command.
SmartExpect is designed to be a minimal, promise-first assertion library with clear, descriptive messaging and easy extensibility:
- Zero-config asynchronous support: chain .resolves / .rejects directly off expect(), add timeouts with .withTimeout(ms), and get clear errors if you mix sync matchers with non-Promises.fast-deep-equal
- Lean, modular footprint: only depends on , @push.rocks/smartpromise, and @push.rocks/smartdelay; pure ESM, tree-shakable, works in Node & browser..not
- Better out-of-the-box messaging: automatic inversion (e.g. “Expected 5 not to be greater than 3”) and unified “Expected… / Received…” JSON diffs for object/array mismatches.toBeNaN
- Rich built-in matchers: numbers (, toBeWithinRange), objects (toHaveKeys, toHaveOwnKeys, shorthand toHaveOwnProperty), strings/arrays (toBeEmpty, toInclude, toHaveLength), functions (toThrowErrorMatching, toThrowErrorWithMessage), dates, and more.expect.extend({ myMatcher })
- Plugin-style extensibility: add custom matchers with without monkey-patching..d.ts
- First-class TypeScript support: full declarations, generic types for sync vs async chains, and autocomplete in editors.
@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.
First, import @push.rocks/smartexpect into your TypeScript file:
`typescript`
import { expect } from '@push.rocks/smartexpect';
You can employ expect to create synchronous assertions:
`typescript
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/);
`
For asynchronous code, use the same expect function with the .resolves or .rejects modifier:
`typescript
import { expect } from '@push.rocks/smartexpect';
const asyncStringFetcher = async (): Promise
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();
`
You can navigate complex objects using the property() and arrayItem() methods:
`typescript
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();
`
#### Properties and Deep Properties
Assert the existence of properties and their values:
`typescript
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:
`typescript
// 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:
`typescript
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:
`typescript`
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:
`typescript
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:
`typescript
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);
`
The log() method is useful for debugging complex assertions:
`typescript`
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();
You can provide custom error messages for more meaningful test failures:
`typescript`
expect(user.age)
.setFailMessage('User age must be at least 18 for adult content')
.toBeGreaterThanOrEqual(18);
You can define your own matchers via expect.extend():
`typescriptExpected ${received} ${pass ? 'not ' : ''}to be odd
expect.extend({
toBeOdd(received: number) {
const pass = received % 2 === 1;
return {
pass,
message: () =>
,
};
},
});
// Then use your custom matcher in tests:
expect(3).toBeOdd();
expect(4).not.toBeOdd();
`
- Matcher functions receive the value under test (received) plus any arguments.pass
- Must return an object with (boolean) and message (string or function) for failure messages.
Below is a comprehensive list of all matchers and utility functions available in @push.rocks/smartexpect.
#### Modifiers and Utilities
- .not Negates the next matcher in the chain..resolves
- Switches to async mode, expecting the promise to resolve..rejects
- Switches to async mode, expecting the promise to reject..withTimeout(ms)
- Sets a timeout (in milliseconds) for async assertions..timeout(ms)
- (deprecated) Alias for .withTimeout(ms)..property(name)
- Drill into a property of an object..arrayItem(index)
- Drill into an array element by index..log()
- Logs the current value and assertion path for debugging..setFailMessage(message)
- Override the failure message for the current assertion..setSuccessMessage(message)
- Override the success message for the current assertion..customAssertion(fn, message)
- Execute a custom assertion function with a message.expect.extend(matchers)
- Register custom matchers globally.expect.any(constructor)
- Matcher for values that are instances of the given constructor.expect.anything()
- Matcher for any defined value (not null or undefined).
#### Basic Matchers
- .toEqual(expected) Deep (or strict for primitives) equality..toBeTrue()
- Value is strictly true..toBeFalse()
- Value is strictly false..toBeTruthy()
- Value is truthy..toBeFalsy()
- Value is falsy..toBeNull()
- Value is null..toBeUndefined()
- Value is undefined..toBeNullOrUndefined()
- Value is null or undefined..toBeDefined()
- Value is not undefined.
#### Number Matchers
- .toBeGreaterThan(value).toBeLessThan(value)
- .toBeGreaterThanOrEqual(value)
- .toBeLessThanOrEqual(value)
- .toBeCloseTo(value, precision?)
- .toEqual(value)
- Strict equality for numbers..toBeNaN()
- .toBeFinite()
- .toBeWithinRange(min, max)
-
#### String Matchers
- .toStartWith(prefix).toEndWith(suffix)
- .toInclude(substring)
- .toMatch(regex)
- .toBeOneOf(arrayOfValues)
- .toHaveLength(length)
- .toBeEmpty()
- Alias for empty string.
#### Array Matchers
- .toBeArray().toHaveLength(length)
- .toContain(value)
- .toContainEqual(value)
- .toContainAll(arrayOfValues)
- .toExclude(value)
- .toBeEmptyArray()
- .toBeEmpty()
- Alias for empty array..toHaveLengthGreaterThan(length)
- .toHaveLengthLessThan(length)
-
#### Object Matchers
- .toEqual(expected) Deep equality for objects..toMatchObject(partialObject)
- Partial deep matching (supports expect.any and expect.anything)..toBeInstanceOf(constructor)
- .toHaveProperty(propertyName, value?)
- .toHaveDeepProperty(pathArray)
- .toHaveOwnProperty(propertyName, value?)
- .toBeNull()
- .toBeUndefined()
- .toBeNullOrUndefined()
-
#### Function Matchers
- .toThrow(expectedError?).toThrowErrorMatching(regex)
- .toThrowErrorWithMessage(message)
-
#### Date Matchers
- .toBeDate().toBeBeforeDate(date)
- .toBeAfterDate(date)
-
#### Type Matchers
- .toBeTypeofString().toBeTypeofNumber()
- .toBeTypeofBoolean()
- .toBeTypeOf(typeName)
-
- Human-readable assertions: The fluent API is designed to create tests that read like natural language sentences.
- Precise error messages: When tests fail, the error messages provide detailed information about what went wrong, including expected vs. actual values.
- Property path navigation: Use the property path methods to navigate complex objects without creating temporary variables.
- Comprehensive testing: Take advantage of the wide range of assertion methods to test various aspects of your code.
- Debugging with log(): Use the log()` method to see intermediate values in the assertion chain during test development.
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.
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.
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
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.