Compare commits
6 Commits
Author | SHA1 | Date | |
---|---|---|---|
4eac4544a5 | |||
47458118a6 | |||
6f1e37cf56 | |||
ed9a9b7f2c | |||
5801d34f18 | |||
f0ab180902 |
@ -119,6 +119,6 @@ jobs:
|
||||
run: |
|
||||
npmci node install stable
|
||||
npmci npm install
|
||||
pnpm install -g @gitzone/tsdoc
|
||||
pnpm install -g @git.zone/tsdoc
|
||||
npmci command tsdoc
|
||||
continue-on-error: true
|
||||
|
23
changelog.md
23
changelog.md
@ -1,5 +1,28 @@
|
||||
# Changelog
|
||||
|
||||
## 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
|
||||
|
||||
- Added packageManager field in package.json
|
||||
- Revised documentation in readme.md to use .resolves/.rejects instead of expectAsync
|
||||
- Included detailed examples for custom matchers and updated API usage
|
||||
- Added readme.plan.md outlining the future roadmap
|
||||
- Updated tests to import the built library from dist_ts
|
||||
|
||||
## 2025-03-04 - 1.6.1 - fix(build)
|
||||
Corrected package.json and workflow dependencies and resolved formatting issues in tests.
|
||||
|
||||
- Fixed incorrect global npm package reference for tsdoc installation in workflow file.
|
||||
- Updated dependencies in package.json for consistency in package naming.
|
||||
- Resolved inconsistent formatting and spacing in test files.
|
||||
|
||||
## 2025-03-04 - 1.6.0 - feat(assertion)
|
||||
Enhanced the assertion error messaging and added new test cases.
|
||||
|
||||
- Improved error messages by incorporating path and value/placeholders in assertions.
|
||||
- Added detailed testing of new assertion functionalities.
|
||||
- Additional test cases for comprehensive coverage of new features.
|
||||
|
||||
## 2025-03-04 - 1.5.0 - feat(Assertion)
|
||||
Add toBeTypeOf assertion method
|
||||
|
||||
|
15
package.json
15
package.json
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@push.rocks/smartexpect",
|
||||
"version": "1.5.0",
|
||||
"version": "2.0.0",
|
||||
"private": false,
|
||||
"description": "A testing library to manage expectations in code, offering both synchronous and asynchronous assertion methods.",
|
||||
"main": "dist_ts/index.js",
|
||||
@ -10,14 +10,14 @@
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"test": "(tstest test/ --web)",
|
||||
"build": "(tsbuild --web)",
|
||||
"build": "(tsbuild tsfolders)",
|
||||
"buildDocs": "tsdoc"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@gitzone/tsbuild": "^2.1.66",
|
||||
"@gitzone/tsbundle": "^2.0.8",
|
||||
"@gitzone/tsrun": "^1.2.44",
|
||||
"@gitzone/tstest": "^1.0.77",
|
||||
"@git.zone/tsbuild": "^2.2.1",
|
||||
"@git.zone/tsbundle": "^2.2.5",
|
||||
"@git.zone/tsrun": "^1.3.3",
|
||||
"@git.zone/tstest": "^1.0.96",
|
||||
"@push.rocks/tapbundle": "^5.5.6",
|
||||
"@types/node": "^22.13.9"
|
||||
},
|
||||
@ -62,5 +62,6 @@
|
||||
"onlyBuiltDependencies": [
|
||||
"mongodb-memory-server"
|
||||
]
|
||||
}
|
||||
},
|
||||
"packageManager": "pnpm@10.7.0+sha512.6b865ad4b62a1d9842b61d674a393903b871d9244954f652b8842c2b553c72176b278f64c463e52d40fff8aba385c235c8c9ecf5cc7de4fd78b8bb6d49633ab6"
|
||||
}
|
||||
|
5031
pnpm-lock.yaml
generated
5031
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
240
readme.md
240
readme.md
@ -1,5 +1,5 @@
|
||||
# @push.rocks/smartexpect
|
||||
manage expectations in code
|
||||
Manage expectations in code with precise, readable assertions
|
||||
|
||||
## Install
|
||||
|
||||
@ -30,14 +30,16 @@ You can employ `expect` to create synchronous assertions:
|
||||
```typescript
|
||||
import { expect } from '@push.rocks/smartexpect';
|
||||
|
||||
// String type assertion
|
||||
// Type assertions
|
||||
expect('hello').toBeTypeofString();
|
||||
|
||||
// Negated String type assertion
|
||||
expect(1).not.toBeTypeofString();
|
||||
|
||||
// Boolean type assertion
|
||||
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');
|
||||
@ -51,78 +53,218 @@ expect('hithere').toMatch(/hi/);
|
||||
|
||||
### Asynchronous Expectations
|
||||
|
||||
For asynchronous operations, use `expectAsync` to return a promise:
|
||||
For asynchronous code, use the same `expect` function with the `.resolves` or `.rejects` modifier:
|
||||
|
||||
```typescript
|
||||
import { expectAsync } from '@push.rocks/smartexpect';
|
||||
import { expect } from '@push.rocks/smartexpect';
|
||||
|
||||
const asyncStringFetcher = async (): Promise<string> => {
|
||||
return 'async string';
|
||||
};
|
||||
|
||||
const asyncTest = async () => {
|
||||
await expectAsync(asyncStringFetcher()).toBeTypeofString();
|
||||
await expectAsync(asyncStringFetcher()).toEqual('async string');
|
||||
// Add a timeout to prevent hanging tests
|
||||
await expect(asyncStringFetcher()).resolves.withTimeout(5000).type.toBeTypeofString();
|
||||
await expect(asyncStringFetcher()).resolves.toEqual('async string');
|
||||
};
|
||||
|
||||
asyncTest();
|
||||
```
|
||||
|
||||
### Advanced Usage
|
||||
### Navigating Complex Objects
|
||||
|
||||
- **Properties and Deep Properties:** Assert the existence of properties and their values.
|
||||
|
||||
```typescript
|
||||
const testObject = { level1: { level2: 'value' } };
|
||||
You can navigate complex objects using the `property()` and `arrayItem()` methods:
|
||||
|
||||
// Property existence
|
||||
expect(testObject).toHaveProperty('level1');
|
||||
|
||||
// Deep Property existence
|
||||
expect(testObject).toHaveDeepProperty(['level1', 'level2']);
|
||||
```
|
||||
```typescript
|
||||
const complexObject = {
|
||||
users: [
|
||||
{ id: 1, name: 'Alice', permissions: { admin: true } },
|
||||
{ id: 2, name: 'Bob', permissions: { admin: false } }
|
||||
]
|
||||
};
|
||||
|
||||
- **Conditions and Comparisons:** Allow more intricate assertions like greater than, less than, or matching specific conditions.
|
||||
// Navigate to a nested property
|
||||
expect(complexObject)
|
||||
.property('users')
|
||||
.arrayItem(0)
|
||||
.property('name')
|
||||
.toEqual('Alice');
|
||||
|
||||
```typescript
|
||||
// Greater Than
|
||||
expect(5).toBeGreaterThan(3);
|
||||
// Check nested permission
|
||||
expect(complexObject)
|
||||
.property('users')
|
||||
.arrayItem(0)
|
||||
.property('permissions')
|
||||
.property('admin')
|
||||
.toBeTrue();
|
||||
```
|
||||
|
||||
// Less Than
|
||||
expect(3).toBeLessThan(5);
|
||||
### Advanced Assertions
|
||||
|
||||
// Custom conditions
|
||||
expect(7).customAssertion(value => value > 5, 'Value is not greater than 5');
|
||||
```
|
||||
#### Properties and Deep Properties
|
||||
|
||||
- **Arrays and Objects:** Work seamlessly with arrays and objects, checking for containment, length, or specific values.
|
||||
Assert the existence of properties and their values:
|
||||
|
||||
```typescript
|
||||
const testArray = [1, 2, 3];
|
||||
```typescript
|
||||
const testObject = { level1: { level2: 'value' } };
|
||||
|
||||
// Containment
|
||||
expect(testArray).toContain(2);
|
||||
// Property existence
|
||||
expect(testObject).toHaveProperty('level1');
|
||||
|
||||
// Array length
|
||||
expect(testArray).toHaveLength(3);
|
||||
// Property with specific value
|
||||
expect(testObject).toHaveProperty('level1.level2', 'value');
|
||||
|
||||
// Object matching
|
||||
expect({ name: 'Test', value: 123 }).toMatchObject({ name: 'Test' });
|
||||
```
|
||||
// Deep Property existence
|
||||
expect(testObject).toHaveDeepProperty(['level1', 'level2']);
|
||||
```
|
||||
|
||||
### Handling Promises and Async Operations
|
||||
#### Conditions and Comparisons
|
||||
|
||||
`@push.rocks/smartexpect` gracefully integrates with asynchronous operations, providing a `expectAsync` function that handles promise-based assertions. This keeps your tests clean and readable, irrespective of the nature of the code being tested.
|
||||
Perform more intricate assertions:
|
||||
|
||||
### Best Practices
|
||||
```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
|
||||
|
||||
- **Readability:** Favor clarity and readability by explicitly stating your expectations. `@push.rocks/smartexpect`'s API is designed to be fluent and expressive, making your tests easy to write and, more importantly, easy to read.
|
||||
// Truthiness checks
|
||||
expect(true).toBeTrue();
|
||||
expect(false).toBeFalse();
|
||||
expect('non-empty').toBeTruthy();
|
||||
expect(0).toBeFalsy();
|
||||
|
||||
- **Comprehensive Coverage:** Utilize the full spectrum of assertions provided to cover a broad set of use cases, ensuring your code behaves as expected not just in ideal conditions but across various edge cases.
|
||||
// Null/Undefined checks
|
||||
expect(null).toBeNull();
|
||||
expect(undefined).toBeUndefined();
|
||||
expect(null).toBeNullOrUndefined();
|
||||
|
||||
- **Maintainability:** Group related assertions together to improve test maintainability. This makes it easier to update tests as your codebase evolves.
|
||||
// Custom conditions
|
||||
expect(7).customAssertion(value => value % 2 === 1, 'Value is not odd');
|
||||
```
|
||||
|
||||
Through judicious use of `@push.rocks/smartexpect`, you can enhance the reliability and maintainability of your test suite, making your codebase more robust and your development workflow more efficient.
|
||||
#### 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);
|
||||
```
|
||||
|
||||
### Custom Matchers
|
||||
|
||||
You can define your own matchers via `expect.extend()`:
|
||||
|
||||
```typescript
|
||||
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();
|
||||
```
|
||||
|
||||
- Matcher functions receive the value under test (`received`) plus any arguments.
|
||||
- Must return an object with `pass` (boolean) and `message` (string or function) for failure messages.
|
||||
|
||||
## 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
|
||||
|
||||
@ -141,4 +283,4 @@ 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.
|
||||
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.
|
37
readme.plan.md
Normal file
37
readme.plan.md
Normal file
@ -0,0 +1,37 @@
|
||||
# Plan for Improving @push.rocks/smartexpect API
|
||||
|
||||
This document captures the roadmap for evolving the `expect` / `expectAsync` API.
|
||||
|
||||
## Phase 1: Unify Sync + Async
|
||||
- [x] Consolidate `expect` and `expectAsync` into a single `expect()` entry point.
|
||||
- [x] Introduce `.resolves` and `.rejects` chainable helpers for Promises.
|
||||
- [x] Deprecate `expectAsync`, provide migration guidance.
|
||||
|
||||
## Phase 2: Timeout Helper
|
||||
- [x] Rename or wrap the existing `.timeout(ms)` to a more intuitive `.withTimeout(ms)`.
|
||||
|
||||
## Phase 3: Custom Matchers
|
||||
- [x] Implement `expect.extend()` API for user-defined matchers.
|
||||
|
||||
## Phase 4: TypeScript Typings
|
||||
- [ ] Enhance generic matcher types to infer narrow types after `.property()` / `.arrayItem()`.
|
||||
- [ ] Provide matcher overloads for primitive categories (string, number, array, etc.).
|
||||
|
||||
## Phase 5: Namespaced Matchers
|
||||
- [ ] Group matchers under `.string`, `.array`, `.number`, etc. for discoverability.
|
||||
|
||||
## Phase 6: Jest-Style Convenience
|
||||
- [ ] Add `.toMatchObject()`, `.toMatchSnapshot()`, `expect.any()`, `expect.anything()`, etc.
|
||||
|
||||
## Phase 7: Error Messages & Diffs
|
||||
- [ ] Integrate a diffing library for clear failure output with colorized diffs.
|
||||
|
||||
## Phase 8: Nested Access Chaining
|
||||
- [ ] Provide `.at(path)` or lens-based API for deep property assertions in one go.
|
||||
|
||||
## Phase 9: Pluggable Reporters
|
||||
- [ ] Allow consumers to swap output format: JSON, TAP, HTML, etc.
|
||||
|
||||
## Phase 10: API Cleanup
|
||||
- [ ] Audit and remove legacy aliases and redundant methods.
|
||||
- [ ] Finalize deprecations and bump to a major version.
|
221
test/test.both.ts
Normal file
221
test/test.both.ts
Normal file
@ -0,0 +1,221 @@
|
||||
import { tap } from '@push.rocks/tapbundle';
|
||||
// Import the built library (dist_ts) so all matcher implementations are available
|
||||
import * as smartexpect from '../dist_ts/index.js';
|
||||
|
||||
tap.test('basic type assertions', async () => {
|
||||
// String type checks
|
||||
smartexpect.expect('hello').type.toBeTypeofString();
|
||||
smartexpect.expect(1).not.type.toBeTypeofString();
|
||||
|
||||
// Boolean type checks
|
||||
smartexpect.expect(true).type.toBeTypeofBoolean();
|
||||
smartexpect.expect(false).type.toBeTypeofBoolean();
|
||||
smartexpect.expect(1).not.type.toBeTypeofBoolean();
|
||||
|
||||
// Number type checks
|
||||
smartexpect.expect(42).type.toBeTypeofNumber();
|
||||
smartexpect.expect(true).not.type.toBeTypeofNumber();
|
||||
|
||||
// Generic type checks with new method
|
||||
smartexpect.expect(() => {}).type.toBeTypeOf('function');
|
||||
smartexpect.expect(class Test {}).type.toBeTypeOf('function');
|
||||
smartexpect.expect({}).type.toBeTypeOf('object');
|
||||
smartexpect.expect(Symbol('test')).type.toBeTypeOf('symbol');
|
||||
});
|
||||
|
||||
tap.test('async tests', async (toolsArg) => {
|
||||
const deferred = toolsArg.defer();
|
||||
toolsArg.delayFor(1000).then(() => {
|
||||
deferred.resolve('hello');
|
||||
});
|
||||
// Using .resolves to test promise resolution with timeout
|
||||
await smartexpect.expect(deferred.promise).resolves.withTimeout(2000).type.toBeTypeofString();
|
||||
await smartexpect.expect(deferred.promise).resolves.not.type.toBeTypeofBoolean();
|
||||
|
||||
// Test async timeout handling
|
||||
const longOperation = toolsArg.defer();
|
||||
toolsArg.delayFor(3000).then(() => {
|
||||
longOperation.resolve('completed');
|
||||
});
|
||||
try {
|
||||
// Assert that resolution must occur within timeout
|
||||
await smartexpect.expect(longOperation.promise).resolves.withTimeout(1000).toBeDefined();
|
||||
throw new Error('Should have timed out');
|
||||
} catch (err) {
|
||||
// Successfully caught timeout error from .withTimeout
|
||||
console.log('Successfully caught timeout:', err.message);
|
||||
}
|
||||
});
|
||||
|
||||
tap.test('equality and matching assertions', async () => {
|
||||
// Basic equality
|
||||
smartexpect.expect('hithere').object.toEqual('hithere');
|
||||
smartexpect.expect('hithere').not.object.toEqual('hithere2');
|
||||
|
||||
// Object equality
|
||||
const obj1 = { a: 1, b: { c: true } };
|
||||
const obj2 = { a: 1, b: { c: true } };
|
||||
const obj3 = { a: 1, b: { c: false } };
|
||||
smartexpect.expect(obj1).object.toEqual(obj2);
|
||||
smartexpect.expect(obj1).not.object.toEqual(obj3);
|
||||
|
||||
// RegExp matching
|
||||
smartexpect.expect('hithere').string.toMatch(/hi/);
|
||||
smartexpect.expect('hithere').string.toMatch(/^hithere$/);
|
||||
smartexpect.expect('hithere').not.string.toMatch(/ho/);
|
||||
|
||||
// String inclusion
|
||||
smartexpect.expect('hithere').string.toInclude('hit');
|
||||
smartexpect.expect('hithere').not.string.toInclude('missing');
|
||||
|
||||
// String start/end
|
||||
smartexpect.expect('hithere').string.toStartWith('hi');
|
||||
smartexpect.expect('hithere').string.toEndWith('ere');
|
||||
});
|
||||
|
||||
tap.test('object property assertions', async () => {
|
||||
const testObject = {
|
||||
topLevel: 'hello',
|
||||
nested: {
|
||||
prop: 42,
|
||||
deeplyNested: {
|
||||
array: [1, 2, 3],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Basic property checks
|
||||
smartexpect.expect(testObject).object.toHaveProperty('topLevel');
|
||||
smartexpect.expect(testObject).object.toHaveProperty('topLevel', 'hello');
|
||||
smartexpect.expect(testObject).not.object.toHaveProperty('missing');
|
||||
|
||||
// Drill-down property navigation
|
||||
smartexpect.expect(testObject).property('nested').object.toHaveProperty('prop', 42);
|
||||
smartexpect
|
||||
.expect(testObject)
|
||||
.property('nested')
|
||||
.property('deeplyNested')
|
||||
.property('array')
|
||||
.array.toBeArray();
|
||||
|
||||
// Deep property checks
|
||||
smartexpect.expect(testObject).object.toHaveDeepProperty(['nested', 'deeplyNested', 'array']);
|
||||
|
||||
// Array item navigation
|
||||
smartexpect
|
||||
.expect(testObject)
|
||||
.property('nested')
|
||||
.property('deeplyNested')
|
||||
.property('array')
|
||||
.arrayItem(0)
|
||||
.number.toEqual(1); // numeric equality via number namespace
|
||||
});
|
||||
|
||||
tap.test('numeric comparison assertions', async () => {
|
||||
// Greater/less than
|
||||
smartexpect.expect(4).number.toBeGreaterThan(3);
|
||||
smartexpect.expect(4).number.toBeLessThan(5);
|
||||
smartexpect.expect(4).number.toBeGreaterThanOrEqual(4);
|
||||
smartexpect.expect(4).number.toBeLessThanOrEqual(4);
|
||||
|
||||
// Approximate equality
|
||||
smartexpect.expect(0.1 + 0.2).number.toBeCloseTo(0.3, 10);
|
||||
});
|
||||
|
||||
tap.test('array assertions', async () => {
|
||||
const obj1 = { id: 1 };
|
||||
const obj2 = { id: 2 };
|
||||
const testArray = [1, 'two', obj1, true];
|
||||
|
||||
// Basic array checks
|
||||
smartexpect.expect(testArray).array.toBeArray();
|
||||
smartexpect.expect(testArray).array.toHaveLength(4);
|
||||
|
||||
// Content checks
|
||||
smartexpect.expect(testArray).array.toContain('two');
|
||||
smartexpect.expect(testArray).array.toContain(obj1);
|
||||
smartexpect.expect(testArray).not.array.toContain(obj2);
|
||||
|
||||
// Array with equal items (not same reference)
|
||||
smartexpect.expect([{ a: 1 }, { b: 2 }]).array.toContainEqual({ a: 1 });
|
||||
|
||||
// Multiple values
|
||||
smartexpect.expect(testArray).array.toContainAll([1, 'two']);
|
||||
smartexpect.expect(testArray).array.toExclude('missing');
|
||||
|
||||
// Empty array
|
||||
smartexpect.expect([]).array.toBeEmptyArray();
|
||||
|
||||
// Length comparisons
|
||||
smartexpect.expect(testArray).array.toHaveLengthGreaterThan(3);
|
||||
smartexpect.expect(testArray).array.toHaveLengthLessThan(5);
|
||||
});
|
||||
|
||||
tap.test('boolean assertions', async () => {
|
||||
// True/False
|
||||
smartexpect.expect(true).boolean.toBeTrue();
|
||||
smartexpect.expect(false).boolean.toBeFalse();
|
||||
|
||||
// Truthy/Falsy
|
||||
smartexpect.expect('something').boolean.toBeTruthy();
|
||||
smartexpect.expect(0).boolean.toBeFalsy();
|
||||
|
||||
// Null/Undefined
|
||||
smartexpect.expect(null).object.toBeNull();
|
||||
smartexpect.expect(undefined).object.toBeUndefined();
|
||||
smartexpect.expect(null).object.toBeNullOrUndefined();
|
||||
smartexpect.expect(undefined).object.toBeNullOrUndefined();
|
||||
});
|
||||
|
||||
tap.test('function assertions', async () => {
|
||||
// Function that throws
|
||||
const throwingFn = () => {
|
||||
throw new Error('test error');
|
||||
};
|
||||
smartexpect.expect(throwingFn).function.toThrow();
|
||||
smartexpect.expect(throwingFn).function.toThrow(Error);
|
||||
|
||||
// Function that doesn't throw
|
||||
const nonThrowingFn = () => 'safe';
|
||||
smartexpect.expect(nonThrowingFn).not.function.toThrow();
|
||||
});
|
||||
|
||||
tap.test('date assertions', async () => {
|
||||
const now = new Date();
|
||||
const past = new Date(Date.now() - 10000);
|
||||
const future = new Date(Date.now() + 10000);
|
||||
|
||||
smartexpect.expect(now).date.toBeDate();
|
||||
smartexpect.expect(now).date.toBeAfterDate(past);
|
||||
smartexpect.expect(now).date.toBeBeforeDate(future);
|
||||
});
|
||||
|
||||
tap.test('custom assertions', async () => {
|
||||
// Custom validation logic
|
||||
smartexpect.expect(42).customAssertion((value) => value % 2 === 0, 'Expected number to be even');
|
||||
|
||||
// With fail message
|
||||
smartexpect.expect('test').setFailMessage('Custom fail message for assertion').string.toHaveLength(4);
|
||||
});
|
||||
|
||||
tap.test('logging and debugging', async () => {
|
||||
// Using log() for debugging
|
||||
const complexObject = {
|
||||
level1: {
|
||||
level2: {
|
||||
value: 'nested value',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// This logs the current value in the chain for debugging
|
||||
smartexpect
|
||||
.expect(complexObject)
|
||||
.property('level1')
|
||||
.property('level2')
|
||||
.log()
|
||||
.property('value')
|
||||
.object.toEqual('nested value');
|
||||
});
|
||||
|
||||
export default tap.start();
|
52
test/test.ts
52
test/test.ts
@ -1,52 +0,0 @@
|
||||
import { tap } from '@push.rocks/tapbundle';
|
||||
import * as smartexpect from '../ts/index.js';
|
||||
|
||||
tap.test('sync tests', async () => {
|
||||
smartexpect.expect('hello').toBeTypeofString();
|
||||
smartexpect.expect(1).not.toBeTypeofString();
|
||||
smartexpect.expect(true).toBeTypeofBoolean();
|
||||
smartexpect.expect(true).not.toBeTypeofNumber();
|
||||
});
|
||||
|
||||
tap.test('async tests', async (toolsArg) => {
|
||||
const deferred = toolsArg.defer();
|
||||
toolsArg.delayFor(4000).then(() => {
|
||||
deferred.resolve('hello');
|
||||
});
|
||||
await smartexpect.expectAsync(deferred.promise).timeout(5000).toBeTypeofString();
|
||||
await smartexpect.expectAsync(deferred.promise).not.toBeTypeofBoolean();
|
||||
});
|
||||
|
||||
tap.test('should check equality', async () => {
|
||||
smartexpect.expect('hithere').toEqual('hithere');
|
||||
smartexpect.expect('hithere').not.toEqual('hithere2');
|
||||
});
|
||||
|
||||
tap.test('should check for regexp matching', async () => {
|
||||
smartexpect.expect('hithere').toMatch(/hi/);
|
||||
smartexpect.expect('hithere').not.toMatch(/ho/);
|
||||
});
|
||||
|
||||
tap.test('should correctly state property presence', async () => {
|
||||
const testObject = {
|
||||
aprop: 'hello',
|
||||
};
|
||||
|
||||
smartexpect.expect(testObject).toHaveProperty('aprop');
|
||||
smartexpect.expect(testObject).not.toHaveProperty('aprop2');
|
||||
});
|
||||
|
||||
tap.test('should be greater than', async () => {
|
||||
smartexpect.expect(4).toBeGreaterThan(3);
|
||||
smartexpect.expect(4).toBeLessThan(5);
|
||||
});
|
||||
|
||||
tap.test('should correctly determine toContain', async () => {
|
||||
const hello = {
|
||||
socool: 'yes',
|
||||
};
|
||||
const testArray = [hello];
|
||||
smartexpect.expect(testArray).toContain(hello);
|
||||
});
|
||||
|
||||
tap.start();
|
@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartexpect',
|
||||
version: '1.5.0',
|
||||
version: '2.0.0',
|
||||
description: 'A testing library to manage expectations in code, offering both synchronous and asynchronous assertion methods.'
|
||||
}
|
||||
|
43
ts/index.ts
43
ts/index.ts
@ -1,12 +1,43 @@
|
||||
import { Assertion } from './smartexpect.classes.assertion.js';
|
||||
// import type { TMatcher } from './smartexpect.classes.assertion.js'; // unused
|
||||
|
||||
export const expect = (baseArg: any) => {
|
||||
const assertion = new Assertion(baseArg, 'sync');
|
||||
return assertion;
|
||||
};
|
||||
/**
|
||||
* Primary entry point for assertions.
|
||||
* Automatically detects Promises to support async assertions.
|
||||
*/
|
||||
/**
|
||||
* The `expect` function interface. Supports custom matchers via .extend.
|
||||
*/
|
||||
/**
|
||||
* Entry point for assertions.
|
||||
* Automatically detects Promises to support async assertions.
|
||||
*/
|
||||
export function expect<T>(value: Promise<T>): Assertion<T>;
|
||||
export function expect<T>(value: T): Assertion<T>;
|
||||
export function expect<T>(value: any): Assertion<T> {
|
||||
const isThenable = value != null && typeof (value as any).then === 'function';
|
||||
const mode: 'sync' | 'async' = isThenable ? 'async' : 'sync';
|
||||
return new Assertion<T>(value, mode);
|
||||
}
|
||||
/**
|
||||
* Register custom matchers.
|
||||
*/
|
||||
export namespace expect {
|
||||
export const extend = Assertion.extend;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use `expect(...)` with `.resolves` or `.rejects` instead.
|
||||
*/
|
||||
/**
|
||||
* @deprecated Use `expect(...)` with `.resolves` or `.rejects` instead.
|
||||
*/
|
||||
/**
|
||||
* @deprecated Use `expect(...)` with `.resolves` or `.rejects` instead.
|
||||
*/
|
||||
export const expectAsync = (baseArg: any) => {
|
||||
const assertion = new Assertion(baseArg, 'async');
|
||||
return assertion;
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn('[DEPRECATED] expectAsync() is deprecated. Use expect(...).resolves / .rejects');
|
||||
return new Assertion<any>(baseArg, 'async');
|
||||
};
|
||||
|
||||
|
44
ts/namespaces/array.ts
Normal file
44
ts/namespaces/array.ts
Normal file
@ -0,0 +1,44 @@
|
||||
import { Assertion } from '../smartexpect.classes.assertion.js';
|
||||
|
||||
/**
|
||||
* Namespace for array-specific matchers
|
||||
*/
|
||||
export class ArrayMatchers<T> {
|
||||
constructor(private assertion: Assertion<T[]>) {}
|
||||
|
||||
toBeArray() {
|
||||
return this.assertion.toBeArray();
|
||||
}
|
||||
|
||||
toHaveLength(length: number) {
|
||||
return this.assertion.toHaveLength(length);
|
||||
}
|
||||
|
||||
toContain(item: T) {
|
||||
return this.assertion.toContain(item);
|
||||
}
|
||||
|
||||
toContainEqual(item: T) {
|
||||
return this.assertion.toContainEqual(item);
|
||||
}
|
||||
|
||||
toContainAll(items: T[]) {
|
||||
return this.assertion.toContainAll(items);
|
||||
}
|
||||
|
||||
toExclude(item: T) {
|
||||
return this.assertion.toExclude(item);
|
||||
}
|
||||
|
||||
toBeEmptyArray() {
|
||||
return this.assertion.toBeEmptyArray();
|
||||
}
|
||||
|
||||
toHaveLengthGreaterThan(length: number) {
|
||||
return this.assertion.toHaveLengthGreaterThan(length);
|
||||
}
|
||||
|
||||
toHaveLengthLessThan(length: number) {
|
||||
return this.assertion.toHaveLengthLessThan(length);
|
||||
}
|
||||
}
|
24
ts/namespaces/boolean.ts
Normal file
24
ts/namespaces/boolean.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { Assertion } from '../smartexpect.classes.assertion.js';
|
||||
|
||||
/**
|
||||
* Namespace for boolean-specific matchers
|
||||
*/
|
||||
export class BooleanMatchers {
|
||||
constructor(private assertion: Assertion<boolean>) {}
|
||||
|
||||
toBeTrue() {
|
||||
return this.assertion.toBeTrue();
|
||||
}
|
||||
|
||||
toBeFalse() {
|
||||
return this.assertion.toBeFalse();
|
||||
}
|
||||
|
||||
toBeTruthy() {
|
||||
return this.assertion.toBeTruthy();
|
||||
}
|
||||
|
||||
toBeFalsy() {
|
||||
return this.assertion.toBeFalsy();
|
||||
}
|
||||
}
|
20
ts/namespaces/date.ts
Normal file
20
ts/namespaces/date.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { Assertion } from '../smartexpect.classes.assertion.js';
|
||||
|
||||
/**
|
||||
* Namespace for date-specific matchers
|
||||
*/
|
||||
export class DateMatchers {
|
||||
constructor(private assertion: Assertion<Date>) {}
|
||||
|
||||
toBeDate() {
|
||||
return this.assertion.toBeDate();
|
||||
}
|
||||
|
||||
toBeBeforeDate(date: Date) {
|
||||
return this.assertion.toBeBeforeDate(date);
|
||||
}
|
||||
|
||||
toBeAfterDate(date: Date) {
|
||||
return this.assertion.toBeAfterDate(date);
|
||||
}
|
||||
}
|
12
ts/namespaces/function.ts
Normal file
12
ts/namespaces/function.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { Assertion } from '../smartexpect.classes.assertion.js';
|
||||
|
||||
/**
|
||||
* Namespace for function-specific matchers
|
||||
*/
|
||||
export class FunctionMatchers {
|
||||
constructor(private assertion: Assertion<Function>) {}
|
||||
|
||||
toThrow(expectedError?: any) {
|
||||
return this.assertion.toThrow(expectedError);
|
||||
}
|
||||
}
|
8
ts/namespaces/index.ts
Normal file
8
ts/namespaces/index.ts
Normal file
@ -0,0 +1,8 @@
|
||||
export { StringMatchers } from './string.js';
|
||||
export { ArrayMatchers } from './array.js';
|
||||
export { NumberMatchers } from './number.js';
|
||||
export { BooleanMatchers } from './boolean.js';
|
||||
export { ObjectMatchers } from './object.js';
|
||||
export { FunctionMatchers } from './function.js';
|
||||
export { DateMatchers } from './date.js';
|
||||
export { TypeMatchers } from './type.js';
|
32
ts/namespaces/number.ts
Normal file
32
ts/namespaces/number.ts
Normal file
@ -0,0 +1,32 @@
|
||||
import { Assertion } from '../smartexpect.classes.assertion.js';
|
||||
|
||||
/**
|
||||
* Namespace for number-specific matchers
|
||||
*/
|
||||
export class NumberMatchers {
|
||||
constructor(private assertion: Assertion<number>) {}
|
||||
|
||||
toBeGreaterThan(value: number) {
|
||||
return this.assertion.toBeGreaterThan(value);
|
||||
}
|
||||
|
||||
toBeLessThan(value: number) {
|
||||
return this.assertion.toBeLessThan(value);
|
||||
}
|
||||
|
||||
toBeGreaterThanOrEqual(value: number) {
|
||||
return this.assertion.toBeGreaterThanOrEqual(value);
|
||||
}
|
||||
|
||||
toBeLessThanOrEqual(value: number) {
|
||||
return this.assertion.toBeLessThanOrEqual(value);
|
||||
}
|
||||
|
||||
toBeCloseTo(value: number, precision?: number) {
|
||||
return this.assertion.toBeCloseTo(value, precision);
|
||||
}
|
||||
/** Equality check for numbers */
|
||||
toEqual(value: number) {
|
||||
return this.assertion.toEqual(value);
|
||||
}
|
||||
}
|
39
ts/namespaces/object.ts
Normal file
39
ts/namespaces/object.ts
Normal file
@ -0,0 +1,39 @@
|
||||
import { Assertion } from '../smartexpect.classes.assertion.js';
|
||||
|
||||
/**
|
||||
* Namespace for object-specific matchers
|
||||
*/
|
||||
export class ObjectMatchers<T extends object> {
|
||||
constructor(private assertion: Assertion<T>) {}
|
||||
|
||||
toEqual(expected: any) {
|
||||
return this.assertion.toEqual(expected);
|
||||
}
|
||||
|
||||
toMatchObject(expected: object) {
|
||||
return this.assertion.toMatchObject(expected);
|
||||
}
|
||||
|
||||
toBeInstanceOf(constructor: any) {
|
||||
return this.assertion.toBeInstanceOf(constructor);
|
||||
}
|
||||
|
||||
toHaveProperty(property: string, value?: any) {
|
||||
return this.assertion.toHaveProperty(property, value);
|
||||
}
|
||||
|
||||
toHaveDeepProperty(path: string[]) {
|
||||
return this.assertion.toHaveDeepProperty(path);
|
||||
}
|
||||
toBeNull() {
|
||||
return this.assertion.toBeNull();
|
||||
}
|
||||
|
||||
toBeUndefined() {
|
||||
return this.assertion.toBeUndefined();
|
||||
}
|
||||
|
||||
toBeNullOrUndefined() {
|
||||
return this.assertion.toBeNullOrUndefined();
|
||||
}
|
||||
}
|
32
ts/namespaces/string.ts
Normal file
32
ts/namespaces/string.ts
Normal file
@ -0,0 +1,32 @@
|
||||
import { Assertion } from '../smartexpect.classes.assertion.js';
|
||||
|
||||
/**
|
||||
* Namespace for string-specific matchers
|
||||
*/
|
||||
export class StringMatchers {
|
||||
constructor(private assertion: Assertion<string>) {}
|
||||
|
||||
toStartWith(prefix: string) {
|
||||
return this.assertion.toStartWith(prefix);
|
||||
}
|
||||
|
||||
toEndWith(suffix: string) {
|
||||
return this.assertion.toEndWith(suffix);
|
||||
}
|
||||
|
||||
toInclude(substring: string) {
|
||||
return this.assertion.toInclude(substring);
|
||||
}
|
||||
|
||||
toMatch(regex: RegExp) {
|
||||
return this.assertion.toMatch(regex);
|
||||
}
|
||||
|
||||
toBeOneOf(values: string[]) {
|
||||
return this.assertion.toBeOneOf(values);
|
||||
}
|
||||
/** Length check for strings */
|
||||
toHaveLength(length: number) {
|
||||
return this.assertion.toHaveLength(length);
|
||||
}
|
||||
}
|
28
ts/namespaces/type.ts
Normal file
28
ts/namespaces/type.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import { Assertion } from '../smartexpect.classes.assertion.js';
|
||||
|
||||
/**
|
||||
* Namespace for type-based matchers
|
||||
*/
|
||||
export class TypeMatchers {
|
||||
constructor(private assertion: Assertion<any>) {}
|
||||
|
||||
toBeTypeofString() {
|
||||
return this.assertion.toBeTypeofString();
|
||||
}
|
||||
|
||||
toBeTypeofNumber() {
|
||||
return this.assertion.toBeTypeofNumber();
|
||||
}
|
||||
|
||||
toBeTypeofBoolean() {
|
||||
return this.assertion.toBeTypeofBoolean();
|
||||
}
|
||||
|
||||
toBeTypeOf(typeName: string) {
|
||||
return this.assertion.toBeTypeOf(typeName);
|
||||
}
|
||||
|
||||
toBeDefined() {
|
||||
return this.assertion.toBeDefined();
|
||||
}
|
||||
}
|
@ -1,9 +1,7 @@
|
||||
import * as smartdelay from '@push.rocks/smartdelay';
|
||||
import * as smartpromise from '@push.rocks/smartpromise';
|
||||
|
||||
export { smartdelay, smartpromise };
|
||||
|
||||
// third party scope
|
||||
// third party utilities
|
||||
import fastDeepEqual from 'fast-deep-equal';
|
||||
|
||||
export { fastDeepEqual };
|
||||
export { fastDeepEqual };
|
@ -1,14 +1,36 @@
|
||||
import * as plugins from './smartexpect.plugins.js';
|
||||
import * as plugins from './plugins.js';
|
||||
import {
|
||||
StringMatchers,
|
||||
ArrayMatchers,
|
||||
NumberMatchers,
|
||||
BooleanMatchers,
|
||||
ObjectMatchers,
|
||||
FunctionMatchers,
|
||||
DateMatchers,
|
||||
TypeMatchers,
|
||||
} from './namespaces/index.js';
|
||||
/**
|
||||
* Definition of a custom matcher function.
|
||||
* Should return an object with `pass` and optional `message`.
|
||||
*/
|
||||
import type { TMatcher, TExecutionType } from './types.js';
|
||||
|
||||
export type TExecutionType = 'sync' | 'async';
|
||||
|
||||
export class Assertion {
|
||||
/**
|
||||
* Core assertion class. Generic over the current value type T.
|
||||
*/
|
||||
export class Assertion<T = unknown> {
|
||||
executionMode: TExecutionType;
|
||||
baseReference: any;
|
||||
propertyDrillDown: Array<string | number> = [];
|
||||
|
||||
private notSetting = false;
|
||||
private timeoutSetting = 0;
|
||||
/** Registry of user-defined custom matchers */
|
||||
private static customMatchers: Record<string, TMatcher> = {};
|
||||
/** Flag for Promise rejection assertions */
|
||||
private isRejects = false;
|
||||
/** Flag for Promise resolution assertions (default for async) */
|
||||
private isResolves = false;
|
||||
private failMessage: string;
|
||||
private successMessage: string;
|
||||
|
||||
@ -16,6 +38,32 @@ export class Assertion {
|
||||
this.baseReference = baseReferenceArg;
|
||||
this.executionMode = executionModeArg;
|
||||
}
|
||||
/**
|
||||
* Register custom matchers to be available on all assertions.
|
||||
* @param matchers An object whose keys are matcher names and values are matcher functions.
|
||||
*/
|
||||
public static extend(matchers: Record<string, TMatcher>): void {
|
||||
for (const [name, fn] of Object.entries(matchers)) {
|
||||
if ((Assertion.prototype as any)[name]) {
|
||||
throw new Error(`Cannot extend. Matcher '${name}' already exists on Assertion.`);
|
||||
}
|
||||
// store in registry
|
||||
Assertion.customMatchers[name] = fn;
|
||||
// add method to prototype
|
||||
(Assertion.prototype as any)[name] = function (...args: any[]) {
|
||||
return this.runCheck(() => {
|
||||
const received = this.getObjectToTestReference();
|
||||
const result = fn(received, ...args);
|
||||
const pass = result.pass;
|
||||
const msg = result.message;
|
||||
if (!pass) {
|
||||
const message = typeof msg === 'function' ? msg() : msg;
|
||||
throw new Error(message || `Custom matcher '${name}' failed`);
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private getObjectToTestReference() {
|
||||
let returnObjectToTestReference = this.baseReference;
|
||||
@ -33,12 +81,94 @@ export class Assertion {
|
||||
return returnObjectToTestReference;
|
||||
}
|
||||
|
||||
private formatDrillDown(): string {
|
||||
if (!this.propertyDrillDown || this.propertyDrillDown.length === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const path = this.propertyDrillDown.map(prop => {
|
||||
if (typeof prop === 'number') {
|
||||
return `[${prop}]`;
|
||||
} else {
|
||||
return `.${prop}`;
|
||||
}
|
||||
}).join('');
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
private formatValue(value: any): string {
|
||||
if (value === null) {
|
||||
return 'null';
|
||||
} else if (value === undefined) {
|
||||
return 'undefined';
|
||||
} else if (typeof value === 'object') {
|
||||
try {
|
||||
return JSON.stringify(value);
|
||||
} catch (e) {
|
||||
return `[Object ${value.constructor.name}]`;
|
||||
}
|
||||
} else if (typeof value === 'function') {
|
||||
return `[Function${value.name ? ': ' + value.name : ''}]`;
|
||||
} else if (typeof value === 'string') {
|
||||
return `"${value}"`;
|
||||
} else {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
private createErrorMessage(message: string): string {
|
||||
if (this.failMessage) {
|
||||
return this.failMessage;
|
||||
}
|
||||
|
||||
const testValue = this.getObjectToTestReference();
|
||||
const formattedValue = this.formatValue(testValue);
|
||||
const drillDown = this.formatDrillDown();
|
||||
|
||||
// Replace placeholders in the message
|
||||
return message
|
||||
.replace('{value}', formattedValue)
|
||||
.replace('{path}', drillDown || '');
|
||||
}
|
||||
|
||||
public get not() {
|
||||
this.notSetting = true;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Assert that a Promise resolves.
|
||||
*/
|
||||
public get resolves(): this {
|
||||
this.isResolves = true;
|
||||
this.isRejects = false;
|
||||
this.executionMode = 'async';
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Assert that a Promise rejects.
|
||||
*/
|
||||
public get rejects(): this {
|
||||
this.isRejects = true;
|
||||
this.isResolves = false;
|
||||
this.executionMode = 'async';
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated use `.withTimeout(ms)` instead for clarity
|
||||
* Set a timeout (in ms) for async assertions (Promise must settle before timeout).
|
||||
*/
|
||||
public timeout(millisArg: number) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn('[DEPRECATED] .timeout() is deprecated. Use .withTimeout(ms)');
|
||||
this.timeoutSetting = millisArg;
|
||||
return this;
|
||||
}
|
||||
/**
|
||||
* Set a timeout (in ms) for async assertions (Promise must settle before timeout).
|
||||
*/
|
||||
public withTimeout(millisArg: number) {
|
||||
this.timeoutSetting = millisArg;
|
||||
return this;
|
||||
}
|
||||
@ -65,601 +195,59 @@ export class Assertion {
|
||||
isOk = true;
|
||||
}
|
||||
if (!isOk) {
|
||||
throw new Error(this.failMessage || 'Negated assertion is not ok!');
|
||||
throw new Error(this.failMessage || 'Negated assertion failed');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (this.executionMode === 'async') {
|
||||
const done = plugins.smartpromise.defer();
|
||||
if (!(this.baseReference instanceof Promise)) {
|
||||
done.reject(new Error(`${this.baseReference} is not of type promise.`));
|
||||
} else {
|
||||
if (this.timeoutSetting) {
|
||||
plugins.smartdelay.delayFor(this.timeoutSetting).then(() => {
|
||||
if (done.status === 'pending') {
|
||||
done.reject(new Error(`${this.baseReference} timed out at ${this.timeoutSetting}!`));
|
||||
}
|
||||
});
|
||||
}
|
||||
this.baseReference.then((promiseResultArg: any) => {
|
||||
this.baseReference = promiseResultArg;
|
||||
done.resolve(runDirectOrNegated(checkFunction));
|
||||
const isThenable = this.baseReference && typeof (this.baseReference as any).then === 'function';
|
||||
if (!isThenable) {
|
||||
done.reject(new Error(`Expected a Promise but received: ${this.formatValue(this.baseReference)}`));
|
||||
return done.promise;
|
||||
}
|
||||
if (this.timeoutSetting) {
|
||||
plugins.smartdelay.delayFor(this.timeoutSetting).then(() => {
|
||||
if (done.status === 'pending') {
|
||||
done.reject(new Error(`Promise timed out after ${this.timeoutSetting}ms`));
|
||||
}
|
||||
});
|
||||
}
|
||||
if (this.isRejects) {
|
||||
(this.baseReference as Promise<any>).then(
|
||||
(res: any) => {
|
||||
done.reject(new Error(`Expected Promise to reject but it resolved with ${this.formatValue(res)}`));
|
||||
},
|
||||
(err: any) => {
|
||||
this.baseReference = err;
|
||||
try {
|
||||
const ret = runDirectOrNegated(checkFunction);
|
||||
done.resolve(ret);
|
||||
} catch (e: any) {
|
||||
done.reject(e);
|
||||
}
|
||||
}
|
||||
);
|
||||
} else {
|
||||
(this.baseReference as Promise<any>).then(
|
||||
(res: any) => {
|
||||
this.baseReference = res;
|
||||
try {
|
||||
const ret = runDirectOrNegated(checkFunction);
|
||||
done.resolve(ret);
|
||||
} catch (e: any) {
|
||||
done.reject(e);
|
||||
}
|
||||
},
|
||||
(err: any) => {
|
||||
done.reject(err);
|
||||
}
|
||||
);
|
||||
}
|
||||
return done.promise;
|
||||
} else {
|
||||
return runDirectOrNegated(checkFunction);
|
||||
}
|
||||
}
|
||||
|
||||
public toBeDefined() {
|
||||
return this.runCheck(() => {
|
||||
if (this.getObjectToTestReference() === undefined) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not defined`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeTypeofString() {
|
||||
return this.runCheck(() => {
|
||||
if (typeof this.getObjectToTestReference() !== 'string') {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`Assertion failed: ${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} is not of type string, but typeof ${typeof this.baseReference}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeTypeofNumber() {
|
||||
return this.runCheck(() => {
|
||||
if (typeof this.getObjectToTestReference() !== 'number') {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`Assertion failed: ${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} is not of type string, but typeof ${typeof this.baseReference}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeTypeofBoolean() {
|
||||
return this.runCheck(() => {
|
||||
if (typeof this.getObjectToTestReference() !== 'boolean') {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`Assertion failed: ${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} is not of type string, but typeof ${typeof this.baseReference}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toEqual(comparisonObject: any) {
|
||||
return this.runCheck(() => {
|
||||
const result = plugins.fastDeepEqual(this.getObjectToTestReference(), comparisonObject);
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} does not equal ${comparisonObject}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toMatch(comparisonObject: RegExp) {
|
||||
return this.runCheck(() => {
|
||||
const result = comparisonObject.test(this.getObjectToTestReference());
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} does not match regex ${comparisonObject}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeTrue() {
|
||||
return this.runCheck(() => {
|
||||
const result =
|
||||
typeof this.getObjectToTestReference() === 'boolean' &&
|
||||
this.getObjectToTestReference() === true;
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not true or not of type boolean`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeFalse() {
|
||||
return this.runCheck(() => {
|
||||
const result =
|
||||
typeof this.getObjectToTestReference() === 'boolean' &&
|
||||
this.getObjectToTestReference() === false;
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not false or not of type boolean`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeInstanceOf(classArg: any) {
|
||||
return this.runCheck(() => {
|
||||
const result = this.getObjectToTestReference() instanceof classArg;
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not an instance of ${classArg}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeTypeOf(expectedType: string) {
|
||||
return this.runCheck(() => {
|
||||
const actualType = typeof this.getObjectToTestReference();
|
||||
if (actualType !== expectedType) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`Assertion failed: ${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} is not of type ${expectedType}, but typeof ${actualType}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toHaveProperty(propertyArg: string, equalsArg?: any) {
|
||||
return this.runCheck(() => {
|
||||
const obj = this.getObjectToTestReference();
|
||||
if (!obj || !(propertyArg in obj)) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} does not have property ${propertyArg}`
|
||||
);
|
||||
}
|
||||
if (equalsArg !== undefined) {
|
||||
if (obj[propertyArg] !== equalsArg) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} does have property ${propertyArg}, but it does not equal ${equalsArg}`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toHaveDeepProperty(properties: string[]) {
|
||||
return this.runCheck(() => {
|
||||
let obj = this.getObjectToTestReference();
|
||||
let currentPath = '';
|
||||
|
||||
for (const property of properties) {
|
||||
if (currentPath) {
|
||||
currentPath += `.${property}`;
|
||||
} else {
|
||||
currentPath = property;
|
||||
}
|
||||
|
||||
if (!obj || !(property in obj)) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`Missing property at path "${currentPath}" in ${this.baseReference}`
|
||||
);
|
||||
}
|
||||
obj = obj[property];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeGreaterThan(numberArg: number) {
|
||||
return this.runCheck(() => {
|
||||
const result = this.getObjectToTestReference() > numberArg;
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not greater than ${numberArg}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeLessThan(numberArg: number) {
|
||||
return this.runCheck(() => {
|
||||
const result = this.getObjectToTestReference() < numberArg;
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not less than ${numberArg}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeNull() {
|
||||
return this.runCheck(() => {
|
||||
const result = this.getObjectToTestReference() === null;
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not null`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeUndefined() {
|
||||
return this.runCheck(() => {
|
||||
const result = this.getObjectToTestReference() === undefined;
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not undefined`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeNullOrUndefined() {
|
||||
return this.runCheck(() => {
|
||||
const testRef = this.getObjectToTestReference();
|
||||
const result = testRef === null || testRef === undefined;
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not null or undefined`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Array checks
|
||||
|
||||
public toContain(itemArg: any) {
|
||||
return this.runCheck(() => {
|
||||
const testRef = this.getObjectToTestReference();
|
||||
const result = Array.isArray(testRef) && testRef.includes(itemArg);
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} does not contain ${itemArg}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeEmptyArray() {
|
||||
return this.runCheck(() => {
|
||||
const arrayRef = this.getObjectToTestReference();
|
||||
if (!Array.isArray(arrayRef) || arrayRef.length !== 0) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`Expected ${this.baseReference} to be an empty array, but it was not.`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toContainAll(values: any[]) {
|
||||
return this.runCheck(() => {
|
||||
const arrayRef = this.getObjectToTestReference();
|
||||
if (!Array.isArray(arrayRef)) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`Expected ${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} to be an array.`
|
||||
);
|
||||
}
|
||||
for (const value of values) {
|
||||
if (!arrayRef.includes(value)) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`Expected ${this.baseReference} to include value "${value}", but it did not.`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toExclude(value: any) {
|
||||
return this.runCheck(() => {
|
||||
const arrayRef = this.getObjectToTestReference();
|
||||
if (!Array.isArray(arrayRef)) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`Expected ${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} to be an array.`
|
||||
);
|
||||
}
|
||||
if (arrayRef.includes(value)) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`Expected ${this.baseReference} to exclude value "${value}", but it included it.`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toStartWith(itemArg: any) {
|
||||
return this.runCheck(() => {
|
||||
const testObject = this.getObjectToTestReference();
|
||||
const result = typeof testObject === 'string' && testObject.startsWith(itemArg);
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} does not start with ${itemArg}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toEndWith(itemArg: any) {
|
||||
return this.runCheck(() => {
|
||||
const testObject = this.getObjectToTestReference();
|
||||
const result = typeof testObject === 'string' && testObject.endsWith(itemArg);
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} does not end with ${itemArg}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeOneOf(values: any[]) {
|
||||
return this.runCheck(() => {
|
||||
const result = values.includes(this.getObjectToTestReference());
|
||||
if (!result) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not one of ${values}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toHaveLength(length: number) {
|
||||
return this.runCheck(() => {
|
||||
const obj = this.getObjectToTestReference();
|
||||
if (typeof obj.length !== 'number' || obj.length !== length) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} does not have a length of ${length}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeCloseTo(value: number, precision = 2) {
|
||||
return this.runCheck(() => {
|
||||
const difference = Math.abs(this.getObjectToTestReference() - value);
|
||||
if (difference > Math.pow(10, -precision) / 2) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} is not close to ${value} up to ${precision} decimal places`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toThrow(expectedError?: any) {
|
||||
return this.runCheck(() => {
|
||||
let thrown = false;
|
||||
try {
|
||||
this.getObjectToTestReference()();
|
||||
} catch (e) {
|
||||
thrown = true;
|
||||
if (expectedError && !(e instanceof expectedError)) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`Expected function to throw ${expectedError.name}, but it threw ${e.name}`
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!thrown) {
|
||||
throw new Error(`Expected function to throw, but it didn't.`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeTruthy() {
|
||||
return this.runCheck(() => {
|
||||
if (!this.getObjectToTestReference()) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not truthy`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeFalsy() {
|
||||
return this.runCheck(() => {
|
||||
if (this.getObjectToTestReference()) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not falsy`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeGreaterThanOrEqual(numberArg: number) {
|
||||
return this.runCheck(() => {
|
||||
if (this.getObjectToTestReference() < numberArg) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} is not greater than or equal to ${numberArg}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeLessThanOrEqual(numberArg: number) {
|
||||
return this.runCheck(() => {
|
||||
if (this.getObjectToTestReference() > numberArg) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} is not less than or equal to ${numberArg}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toMatchObject(objectArg: object) {
|
||||
return this.runCheck(() => {
|
||||
// Implement a partial object match if needed.
|
||||
const matchResult = plugins.fastDeepEqual(this.getObjectToTestReference(), objectArg);
|
||||
if (!matchResult) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} does not match the object ${JSON.stringify(objectArg)}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toContainEqual(value: any) {
|
||||
return this.runCheck(() => {
|
||||
const arr = this.getObjectToTestReference();
|
||||
if (!Array.isArray(arr)) {
|
||||
throw new Error(
|
||||
this.failMessage || `Expected ${this.baseReference} to be an array but it is not.`
|
||||
);
|
||||
}
|
||||
const found = arr.some((item: any) => plugins.fastDeepEqual(item, value));
|
||||
if (!found) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} does not contain the value ${JSON.stringify(value)}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeArray() {
|
||||
return this.runCheck(() => {
|
||||
if (!Array.isArray(this.getObjectToTestReference())) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not an array`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toInclude(substring: string) {
|
||||
return this.runCheck(() => {
|
||||
const testRef = this.getObjectToTestReference();
|
||||
if (typeof testRef !== 'string' || !testRef.includes(substring)) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} does not include the substring ${substring}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toHaveLengthGreaterThan(length: number) {
|
||||
return this.runCheck(() => {
|
||||
const obj = this.getObjectToTestReference();
|
||||
if (typeof obj.length !== 'number' || obj.length <= length) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} does not have a length greater than ${length}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toHaveLengthLessThan(length: number) {
|
||||
return this.runCheck(() => {
|
||||
const obj = this.getObjectToTestReference();
|
||||
if (typeof obj.length !== 'number' || obj.length >= length) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${
|
||||
this.propertyDrillDown
|
||||
} does not have a length less than ${length}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeDate() {
|
||||
return this.runCheck(() => {
|
||||
const testRef = this.getObjectToTestReference();
|
||||
if (!(testRef instanceof Date)) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not a date`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeBeforeDate(date: Date) {
|
||||
return this.runCheck(() => {
|
||||
const testRef = this.getObjectToTestReference();
|
||||
if (!(testRef instanceof Date) || testRef >= date) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not before ${date}`
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public toBeAfterDate(date: Date) {
|
||||
return this.runCheck(() => {
|
||||
const testRef = this.getObjectToTestReference();
|
||||
if (!(testRef instanceof Date) || testRef <= date) {
|
||||
throw new Error(
|
||||
this.failMessage ||
|
||||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not after ${date}`
|
||||
);
|
||||
}
|
||||
});
|
||||
return runDirectOrNegated(checkFunction);
|
||||
}
|
||||
|
||||
public customAssertion(
|
||||
@ -667,32 +255,70 @@ export class Assertion {
|
||||
errorMessage: string
|
||||
) {
|
||||
return this.runCheck(() => {
|
||||
if (!assertionFunction(this.getObjectToTestReference())) {
|
||||
const value = this.getObjectToTestReference();
|
||||
if (!assertionFunction(value)) {
|
||||
throw new Error(this.failMessage || errorMessage);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Drill into a property
|
||||
* Drill into a property of an object.
|
||||
* @param propertyName Name of the property to navigate into.
|
||||
* @returns Assertion of the property type.
|
||||
*/
|
||||
public property(propertyNameArg: string) {
|
||||
this.propertyDrillDown.push(propertyNameArg);
|
||||
return this;
|
||||
public property<K extends keyof NonNullable<T>>(propertyName: K): Assertion<NonNullable<T>[K]> {
|
||||
this.propertyDrillDown.push(propertyName as string);
|
||||
return this as unknown as Assertion<NonNullable<T>[K]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drill into an array index
|
||||
* Drill into an array element by index.
|
||||
* @param index Index of the array item.
|
||||
* @returns Assertion of the element type.
|
||||
*/
|
||||
public arrayItem(indexArg: number) {
|
||||
// Save the number (instead of "[index]")
|
||||
this.propertyDrillDown.push(indexArg);
|
||||
return this;
|
||||
public arrayItem(index: number): Assertion<T extends Array<infer U> ? U : unknown> {
|
||||
this.propertyDrillDown.push(index);
|
||||
return this as unknown as Assertion<T extends Array<infer U> ? U : unknown>;
|
||||
}
|
||||
|
||||
public log() {
|
||||
console.log(`this is the object to test:`);
|
||||
console.log(`Current value:`);
|
||||
console.log(JSON.stringify(this.getObjectToTestReference(), null, 2));
|
||||
console.log(`Path: ${this.formatDrillDown() || '(root)'}`);
|
||||
return this;
|
||||
}
|
||||
// Namespaced matcher accessors
|
||||
/** String-specific matchers */
|
||||
public get string() {
|
||||
return new StringMatchers(this as Assertion<string>);
|
||||
}
|
||||
/** Array-specific matchers */
|
||||
public get array() {
|
||||
return new ArrayMatchers<any>(this as Assertion<any[]>);
|
||||
}
|
||||
/** Number-specific matchers */
|
||||
public get number() {
|
||||
return new NumberMatchers(this as Assertion<number>);
|
||||
}
|
||||
/** Boolean-specific matchers */
|
||||
public get boolean() {
|
||||
return new BooleanMatchers(this as Assertion<boolean>);
|
||||
}
|
||||
/** Object-specific matchers */
|
||||
public get object() {
|
||||
return new ObjectMatchers<any>(this as Assertion<object>);
|
||||
}
|
||||
/** Function-specific matchers */
|
||||
public get function() {
|
||||
return new FunctionMatchers(this as Assertion<Function>);
|
||||
}
|
||||
/** Date-specific matchers */
|
||||
public get date() {
|
||||
return new DateMatchers(this as Assertion<Date>);
|
||||
}
|
||||
/** Type-based matchers */
|
||||
public get type() {
|
||||
return new TypeMatchers(this as Assertion<any>);
|
||||
}
|
||||
}
|
13
ts/types.ts
Normal file
13
ts/types.ts
Normal file
@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Common types for smartexpect
|
||||
*/
|
||||
/** Execution mode: sync or async */
|
||||
export type TExecutionType = 'sync' | 'async';
|
||||
/**
|
||||
* Definition of a custom matcher function.
|
||||
* Should return an object with `pass` and optional `message`.
|
||||
*/
|
||||
export type TMatcher = (
|
||||
received: any,
|
||||
...args: any[]
|
||||
) => { pass: boolean; message?: string | (() => string) };
|
@ -1,6 +1,7 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"useDefineForClassFields": false,
|
||||
"target": "ES2022",
|
||||
"module": "NodeNext",
|
||||
|
Reference in New Issue
Block a user