262 lines
7.5 KiB
Markdown
262 lines
7.5 KiB
Markdown
# @push.rocks/smartexpect
|
|
Manage expectations in code with precise, readable assertions
|
|
|
|
## Install
|
|
|
|
To install `@push.rocks/smartexpect`, use the following command in your terminal:
|
|
|
|
```bash
|
|
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.
|
|
|
|
## 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:
|
|
|
|
```typescript
|
|
import { expect, expectAsync } from '@push.rocks/smartexpect';
|
|
```
|
|
|
|
### Synchronous Expectations
|
|
|
|
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/);
|
|
```
|
|
|
|
### Asynchronous Expectations
|
|
|
|
For asynchronous operations, use `expectAsync` to return a promise:
|
|
|
|
```typescript
|
|
import { expectAsync } from '@push.rocks/smartexpect';
|
|
|
|
const asyncStringFetcher = async (): Promise<string> => {
|
|
return 'async string';
|
|
};
|
|
|
|
const asyncTest = async () => {
|
|
// Add a timeout to prevent hanging tests
|
|
await expectAsync(asyncStringFetcher()).timeout(5000).toBeTypeofString();
|
|
await expectAsync(asyncStringFetcher()).toEqual('async string');
|
|
};
|
|
|
|
asyncTest();
|
|
```
|
|
|
|
### Navigating Complex Objects
|
|
|
|
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();
|
|
```
|
|
|
|
### Advanced Assertions
|
|
|
|
#### 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);
|
|
```
|
|
|
|
### Debugging Assertions
|
|
|
|
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();
|
|
```
|
|
|
|
### Customizing Error Messages
|
|
|
|
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);
|
|
```
|
|
|
|
## Best Practices
|
|
|
|
- **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.
|
|
|
|
## License and Legal Information
|
|
|
|
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](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
|
|
|
|
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. |