Compare commits

..

23 Commits

Author SHA1 Message Date
7ae5b4378a 1.4.0 2024-12-30 20:49:27 +01:00
1979d8dd9c feat(Assertion): Add log method to Assertion class 2024-12-30 20:49:27 +01:00
847b106302 1.3.0 2024-12-30 20:33:25 +01:00
38f0996cfa feat(Assertion): now supporting arrays for propertyy drill down 2024-12-30 20:33:24 +01:00
6cab20c36d 1.2.1 2024-08-24 01:42:18 +02:00
689afcbd92 fix(Assertion): Refactor methods for setting failure and success messages 2024-08-24 01:42:17 +02:00
4e9a7b5424 1.2.0 2024-08-24 01:36:24 +02:00
f83c64e1d4 feat(assertions): Add custom fail and success messages for assertions 2024-08-24 01:36:23 +02:00
04e3c1a9ac 1.1.0 2024-08-17 07:27:34 +02:00
9ef1e5120e feat(assertion): Add toBeDefined assertion method 2024-08-17 07:27:32 +02:00
537545766c update description 2024-05-29 14:13:00 +02:00
56d28d04d6 update tsconfig 2024-04-14 17:34:23 +02:00
b7e098f0a7 update npmextra.json: githost 2024-04-01 21:34:56 +02:00
845daccd58 update npmextra.json: githost 2024-04-01 19:58:12 +02:00
5917f25a99 update npmextra.json: githost 2024-03-30 21:47:10 +01:00
8a8b6cb517 1.0.21 2023-08-12 09:55:14 +02:00
c3d9b5621c fix(core): update 2023-08-12 09:55:13 +02:00
e5c47a68dc 1.0.20 2023-08-12 09:54:30 +02:00
3cf4a6566b fix(core): update 2023-08-12 09:54:29 +02:00
113e5f48cb 1.0.19 2023-08-12 09:49:28 +02:00
8a2d34e88a fix(core): update 2023-08-12 09:49:27 +02:00
035138a437 1.0.18 2023-08-11 18:12:04 +02:00
e0a774852e fix(core): update 2023-08-11 18:12:04 +02:00
16 changed files with 7594 additions and 3091 deletions

View File

@ -0,0 +1,66 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

View File

@ -0,0 +1,124 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @gitzone/tsdoc
npmci command tsdoc
continue-on-error: true

View File

@ -1,104 +0,0 @@
name: CI Pipeline
on: push
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: $
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
test:
needs: security
runs-on: ubuntu-latest
container:
image: $
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: $
steps:
- uses: actions/checkout@v3
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: $
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm prepare
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
npmci command npm run buildDocs
- name: Upload artifacts
uses: actions/upload-artifact@v2
with:
name: public
path: public
retention-days: 7

View File

@ -1,128 +0,0 @@
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: '$CI_BUILD_STAGE'
stages:
- security
- test
- release
- metadata
before_script:
- pnpm install -g pnpm
- pnpm install -g @shipzone/npmci
- npmci npm prepare
# ====================
# security stage
# ====================
# ====================
# security stage
# ====================
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci command npm config set registry https://registry.npmjs.org
- npmci command pnpm audit --audit-level=high --prod
tags:
- lossless
- docker
allow_failure: true
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci command npm config set registry https://registry.npmjs.org
- npmci command pnpm audit --audit-level=high --dev
tags:
- lossless
- docker
allow_failure: true
# ====================
# test stage
# ====================
testStable:
stage: test
script:
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
testBuild:
stage: test
script:
- npmci node install stable
- npmci npm install
- npmci npm build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- lossless
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
allow_failure: true
only:
- tags
script:
- npmci command npm install -g typescript
- npmci npm prepare
- npmci npm install
tags:
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
stage: metadata
script:
- npmci node install stable
- npmci npm install
- npmci command npm run buildDocs
tags:
- lossless
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

67
changelog.md Normal file
View File

@ -0,0 +1,67 @@
# Changelog
## 2024-12-30 - 1.4.0 - feat(Assertion)
Add log method to Assertion class
- Introduced a log method in the Assertion class to output assertion context.
## 2024-12-30 - 1.3.0 - feat(Assertion)
Refactor Assertion class for better error handling and code clarity
- Improved method runCheck to better handle async and sync execution
- Enhanced getObjectToTestReference to handle undefined or null values gracefully
- Refactored error message logic for clarity and added more descriptive fail messages
- Added arrayItem method for better handling of array index access
- Improved structure by integrating consistent error handling in assertion methods
## 2024-08-24 - 1.2.1 - fix(Assertion)
Refactor methods for setting failure and success messages
- Renamed 'withFailMessage' to 'setFailMessage' for better readability and consistency.
- Renamed 'withSuccessMessage' to 'setSuccessMessage' to align with the naming convention.
## 2024-08-24 - 1.2.0 - feat(assertions)
Add custom fail and success messages for assertions
- Implemented withFailMessage method in Assertion class to customize fail messages
- Implemented withSuccessMessage method in Assertion class to customize success messages
- Enhanced error messages to use custom fail messages when provided
## 2024-08-17 - 1.1.0 - feat(assertion)
Add toBeDefined assertion method
- Added the toBeDefined method to the Assertion class for checking if an object is defined
## 2024-05-29 - 1.0.21 - General Updates
General updates and maintenance.
- Updated description
- Updated tsconfig
- Updated npmextra.json: githost
## 2023-08-12 - 1.0.20 to 1.0.21 - General Fixes
General fixes and update.
- Fixed core updates (multiple instances)
- 1.0.21 release
## 2023-07-10 - 1.0.15 - Organization Update
- Switched to new org scheme
## 2023-06-22 - 1.0.14 to 1.0.19 - General Updates
General fixes and updates.
- Fixed core updates (multiple instances)
- 1.0.18 to 1.0.16 releases
## 2022-02-02 - 1.0.8 to 1.0.13 - General Fixes
General fixes and update.
- Fixed core updates (multiple instances)
- 1.0.14 release
## 2022-01-20 - 1.0.1 to 1.0.7 - Initial Releases
Initial core updates and fixes.
- Fixed core updates (multiple instances)
- 1.0.7 release

View File

@ -2,17 +2,32 @@
"gitzone": { "gitzone": {
"projectType": "npm", "projectType": "npm",
"module": { "module": {
"githost": "gitlab.com", "githost": "code.foss.global",
"gitscope": "push.rocks", "gitscope": "push.rocks",
"gitrepo": "smartexpect", "gitrepo": "smartexpect",
"description": "manage expectations in code", "description": "A testing library to manage expectations in code, offering both synchronous and asynchronous assertion methods.",
"npmPackagename": "@push.rocks/smartexpect", "npmPackagename": "@push.rocks/smartexpect",
"license": "MIT", "license": "MIT",
"projectDomain": "push.rocks" "projectDomain": "push.rocks",
"keywords": [
"testing",
"assertions",
"code quality",
"unit testing",
"test driven development",
"synchronous testing",
"asynchronous testing",
"expectations",
"validation",
"development tools"
]
} }
}, },
"npmci": { "npmci": {
"npmGlobalTools": [], "npmGlobalTools": [],
"npmAccessLevel": "public" "npmAccessLevel": "public"
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis 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. \n\n**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.\n\n### Trademarks\n\nThis 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.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy 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.\n"
} }
} }

View File

@ -1,8 +1,8 @@
{ {
"name": "@push.rocks/smartexpect", "name": "@push.rocks/smartexpect",
"version": "1.0.17", "version": "1.4.0",
"private": false, "private": false,
"description": "manage expectations in code", "description": "A testing library to manage expectations in code, offering both synchronous and asynchronous assertion methods.",
"main": "dist_ts/index.js", "main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts", "typings": "dist_ts/index.d.ts",
"type": "module", "type": "module",
@ -16,16 +16,14 @@
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.66", "@gitzone/tsbuild": "^2.1.66",
"@gitzone/tsbundle": "^2.0.8", "@gitzone/tsbundle": "^2.0.8",
"@gitzone/tsrun": "^1.2.42", "@gitzone/tsrun": "^1.2.44",
"@gitzone/tstest": "^1.0.74", "@gitzone/tstest": "^1.0.77",
"@pushrocks/tapbundle": "^5.0.4", "@push.rocks/tapbundle": "^5.5.0",
"@types/node": "^20.3.1", "@types/node": "^22.9.0"
"tslint": "^6.1.3",
"tslint-config-prettier": "^1.18.0"
}, },
"dependencies": { "dependencies": {
"@pushrocks/smartdelay": "^3.0.1", "@push.rocks/smartdelay": "^3.0.5",
"@pushrocks/smartpromise": "^4.0.2", "@push.rocks/smartpromise": "^4.0.4",
"fast-deep-equal": "^3.1.3" "fast-deep-equal": "^3.1.3"
}, },
"browserslist": [ "browserslist": [
@ -42,5 +40,22 @@
"cli.js", "cli.js",
"npmextra.json", "npmextra.json",
"readme.md" "readme.md"
] ],
"keywords": [
"testing",
"assertions",
"code quality",
"unit testing",
"test driven development",
"synchronous testing",
"asynchronous testing",
"expectations",
"validation",
"development tools"
],
"homepage": "https://code.foss.global/push.rocks/smartexpect",
"repository": {
"type": "git",
"url": "https://code.foss.global/push.rocks/smartexpect.git"
}
} }

9575
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

1
readme.hints.md Normal file
View File

@ -0,0 +1 @@

159
readme.md
View File

@ -1,37 +1,144 @@
# @pushrocks/smartexpect # @push.rocks/smartexpect
manage expectations in code manage expectations in code
## Availabililty and Links ## Install
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartexpect)
* [gitlab.com (source)](https://gitlab.com/pushrocks/smartexpect)
* [github.com (source mirror)](https://github.com/pushrocks/smartexpect)
* [docs (typedoc)](https://pushrocks.gitlab.io/smartexpect/)
## Status for master To install `@push.rocks/smartexpect`, use the following command in your terminal:
Status Category | Status Badge ```bash
-- | -- npm install @push.rocks/smartexpect --save
GitLab Pipelines | [![pipeline status](https://gitlab.com/pushrocks/smartexpect/badges/master/pipeline.svg)](https://lossless.cloud) ```
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/pushrocks/smartexpect/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@pushrocks/smartexpect)](https://lossless.cloud) This will add `@push.rocks/smartexpect` to your project's dependencies. Make sure you're inside your project directory before running this command.
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/pushrocks/smartexpect)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@pushrocks/smartexpect)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@pushrocks/smartexpect)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@pushrocks/smartexpect)](https://lossless.cloud)
## Usage ## Usage
Use TypeScript for best in class intellisense `@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.
## Contribution ### Getting Started
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :) First, import `@push.rocks/smartexpect` into your TypeScript file:
For further information read the linked docs at the top of this readme. ```typescript
import { expect, expectAsync } from '@push.rocks/smartexpect';
```
## Legal ### Synchronous Expectations
> MIT licensed | **©** [Task Venture Capital GmbH](https://task.vc)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy) You can employ `expect` to create synchronous assertions:
```typescript
import { expect } from '@push.rocks/smartexpect';
// String type assertion
expect('hello').toBeTypeofString();
// Negated String type assertion
expect(1).not.toBeTypeofString();
// Boolean type assertion
expect(true).toBeTypeofBoolean();
// 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 () => {
await expectAsync(asyncStringFetcher()).toBeTypeofString();
await expectAsync(asyncStringFetcher()).toEqual('async string');
};
asyncTest();
```
### Advanced Usage
- **Properties and Deep Properties:** Assert the existence of properties and their values.
```typescript
const testObject = { level1: { level2: 'value' } };
// Property existence
expect(testObject).toHaveProperty('level1');
// Deep Property existence
expect(testObject).toHaveDeepProperty(['level1', 'level2']);
```
- **Conditions and Comparisons:** Allow more intricate assertions like greater than, less than, or matching specific conditions.
```typescript
// Greater Than
expect(5).toBeGreaterThan(3);
// Less Than
expect(3).toBeLessThan(5);
// Custom conditions
expect(7).customAssertion(value => value > 5, 'Value is not greater than 5');
```
- **Arrays and Objects:** Work seamlessly with arrays and objects, checking for containment, length, or specific values.
```typescript
const testArray = [1, 2, 3];
// Containment
expect(testArray).toContain(2);
// Array length
expect(testArray).toHaveLength(3);
// Object matching
expect({ name: 'Test', value: 123 }).toMatchObject({ name: 'Test' });
```
### Handling Promises and Async Operations
`@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.
### Best Practices
- **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.
- **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.
- **Maintainability:** Group related assertions together to improve test maintainability. This makes it easier to update tests as your codebase evolves.
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.
## 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.

View File

@ -1,4 +1,4 @@
import { tap } from '@pushrocks/tapbundle'; import { tap } from '@push.rocks/tapbundle';
import * as smartexpect from '../ts/index.js'; import * as smartexpect from '../ts/index.js';
tap.test('sync tests', async () => { tap.test('sync tests', async () => {

View File

@ -1,8 +1,8 @@
/** /**
* autocreated commitinfo by @pushrocks/commitinfo * autocreated commitinfo by @push.rocks/commitinfo
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/smartexpect', name: '@push.rocks/smartexpect',
version: '1.0.17', version: '1.4.0',
description: 'manage expectations in code' description: 'A testing library to manage expectations in code, offering both synchronous and asynchronous assertion methods.'
} }

View File

@ -1,5 +1,3 @@
import * as plugins from './smartexpect.plugins.js';
import { Assertion } from './smartexpect.classes.assertion.js'; import { Assertion } from './smartexpect.classes.assertion.js';
export const expect = (baseArg: any) => { export const expect = (baseArg: any) => {
@ -11,3 +9,4 @@ export const expectAsync = (baseArg: any) => {
const assertion = new Assertion(baseArg, 'async'); const assertion = new Assertion(baseArg, 'async');
return assertion; return assertion;
}; };

View File

@ -5,9 +5,13 @@ export type TExecutionType = 'sync' | 'async';
export class Assertion { export class Assertion {
executionMode: TExecutionType; executionMode: TExecutionType;
baseReference: any; baseReference: any;
propertyDrillDown: string[] = []; propertyDrillDown: Array<string | number> = [];
private notSetting = false; private notSetting = false;
private timeoutSetting = 0; private timeoutSetting = 0;
private failMessage: string;
private successMessage: string;
constructor(baseReferenceArg: any, executionModeArg: TExecutionType) { constructor(baseReferenceArg: any, executionModeArg: TExecutionType) {
this.baseReference = baseReferenceArg; this.baseReference = baseReferenceArg;
this.executionMode = executionModeArg; this.executionMode = executionModeArg;
@ -16,6 +20,14 @@ export class Assertion {
private getObjectToTestReference() { private getObjectToTestReference() {
let returnObjectToTestReference = this.baseReference; let returnObjectToTestReference = this.baseReference;
for (const property of this.propertyDrillDown) { for (const property of this.propertyDrillDown) {
if (returnObjectToTestReference == null) {
// if it's null or undefined, stop
break;
}
// We just directly access with bracket notation.
// If property is a string, it's like obj["someProp"];
// If property is a number, it's like obj[0].
returnObjectToTestReference = returnObjectToTestReference[property]; returnObjectToTestReference = returnObjectToTestReference[property];
} }
return returnObjectToTestReference; return returnObjectToTestReference;
@ -31,6 +43,16 @@ export class Assertion {
return this; return this;
} }
public setFailMessage(failMessageArg: string) {
this.failMessage = failMessageArg;
return this;
}
public setSuccessMessage(successMessageArg: string) {
this.successMessage = successMessageArg;
return this;
}
private runCheck(checkFunction: () => any) { private runCheck(checkFunction: () => any) {
const runDirectOrNegated = (checkFunction: () => any) => { const runDirectOrNegated = (checkFunction: () => any) => {
if (!this.notSetting) { if (!this.notSetting) {
@ -43,7 +65,7 @@ export class Assertion {
isOk = true; isOk = true;
} }
if (!isOk) { if (!isOk) {
throw new Error('Negated assertion is not ok!'); throw new Error(this.failMessage || 'Negated assertion is not ok!');
} }
} }
}; };
@ -60,7 +82,7 @@ export class Assertion {
} }
}); });
} }
this.baseReference.then((promiseResultArg) => { this.baseReference.then((promiseResultArg: any) => {
this.baseReference = promiseResultArg; this.baseReference = promiseResultArg;
done.resolve(runDirectOrNegated(checkFunction)); done.resolve(runDirectOrNegated(checkFunction));
}); });
@ -71,13 +93,25 @@ export class Assertion {
} }
} }
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() { public toBeTypeofString() {
return this.runCheck(() => { return this.runCheck(() => {
if (typeof this.getObjectToTestReference() !== 'string') { if (typeof this.getObjectToTestReference() !== 'string') {
throw new Error( throw new Error(
`Assertion failed: ${this.baseReference} with drill down ${ this.failMessage ||
this.propertyDrillDown `Assertion failed: ${this.baseReference} with drill down ${
} is not of type string, but typeof ${typeof this.baseReference}` this.propertyDrillDown
} is not of type string, but typeof ${typeof this.baseReference}`
); );
} }
}); });
@ -87,9 +121,10 @@ export class Assertion {
return this.runCheck(() => { return this.runCheck(() => {
if (typeof this.getObjectToTestReference() !== 'number') { if (typeof this.getObjectToTestReference() !== 'number') {
throw new Error( throw new Error(
`Assertion failed: ${this.baseReference} with drill down ${ this.failMessage ||
this.propertyDrillDown `Assertion failed: ${this.baseReference} with drill down ${
} is not of type string, but typeof ${typeof this.baseReference}` this.propertyDrillDown
} is not of type string, but typeof ${typeof this.baseReference}`
); );
} }
}); });
@ -99,9 +134,10 @@ export class Assertion {
return this.runCheck(() => { return this.runCheck(() => {
if (typeof this.getObjectToTestReference() !== 'boolean') { if (typeof this.getObjectToTestReference() !== 'boolean') {
throw new Error( throw new Error(
`Assertion failed: ${this.baseReference} with drill down ${ this.failMessage ||
this.propertyDrillDown `Assertion failed: ${this.baseReference} with drill down ${
} is not of type string, but typeof ${typeof this.baseReference}` this.propertyDrillDown
} is not of type string, but typeof ${typeof this.baseReference}`
); );
} }
}); });
@ -112,7 +148,8 @@ export class Assertion {
const result = plugins.fastDeepEqual(this.getObjectToTestReference(), comparisonObject); const result = plugins.fastDeepEqual(this.getObjectToTestReference(), comparisonObject);
if (!result) { if (!result) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not equal ${comparisonObject}` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} does not equal ${comparisonObject}`
); );
} }
}); });
@ -123,7 +160,10 @@ export class Assertion {
const result = comparisonObject.test(this.getObjectToTestReference()); const result = comparisonObject.test(this.getObjectToTestReference());
if (!result) { if (!result) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not equal ${comparisonObject}` this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not match regex ${comparisonObject}`
); );
} }
}); });
@ -136,7 +176,8 @@ export class Assertion {
this.getObjectToTestReference() === true; this.getObjectToTestReference() === true;
if (!result) { if (!result) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not true or not of type boolean` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not true or not of type boolean`
); );
} }
}); });
@ -149,7 +190,8 @@ export class Assertion {
this.getObjectToTestReference() === false; this.getObjectToTestReference() === false;
if (!result) { if (!result) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not false or not of type boolean` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not false or not of type boolean`
); );
} }
}); });
@ -160,7 +202,8 @@ export class Assertion {
const result = this.getObjectToTestReference() instanceof classArg; const result = this.getObjectToTestReference() instanceof classArg;
if (!result) { if (!result) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not an instance of ${classArg}` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not an instance of ${classArg}`
); );
} }
}); });
@ -168,28 +211,58 @@ export class Assertion {
public toHaveProperty(propertyArg: string, equalsArg?: any) { public toHaveProperty(propertyArg: string, equalsArg?: any) {
return this.runCheck(() => { return this.runCheck(() => {
const result = !!this.getObjectToTestReference()[propertyArg]; const obj = this.getObjectToTestReference();
if (!result) { if (!obj || !(propertyArg in obj)) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not have property ${propertyArg}` this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not have property ${propertyArg}`
); );
} }
if (equalsArg) { if (equalsArg !== undefined) {
if (result !== equalsArg) { if (obj[propertyArg] !== equalsArg) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does have property ${propertyArg}, but it does not equal ${equalsArg}` 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) { public toBeGreaterThan(numberArg: number) {
return this.runCheck(() => { return this.runCheck(() => {
const result = this.getObjectToTestReference() > numberArg; const result = this.getObjectToTestReference() > numberArg;
if (!result) { if (!result) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not greater than ${numberArg}` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not greater than ${numberArg}`
); );
} }
}); });
@ -200,7 +273,8 @@ export class Assertion {
const result = this.getObjectToTestReference() < numberArg; const result = this.getObjectToTestReference() < numberArg;
if (!result) { if (!result) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not less than ${numberArg}` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not less than ${numberArg}`
); );
} }
}); });
@ -211,7 +285,8 @@ export class Assertion {
const result = this.getObjectToTestReference() === null; const result = this.getObjectToTestReference() === null;
if (!result) { if (!result) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not null` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not null`
); );
} }
}); });
@ -222,7 +297,8 @@ export class Assertion {
const result = this.getObjectToTestReference() === undefined; const result = this.getObjectToTestReference() === undefined;
if (!result) { if (!result) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not undefined` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not undefined`
); );
} }
}); });
@ -230,24 +306,81 @@ export class Assertion {
public toBeNullOrUndefined() { public toBeNullOrUndefined() {
return this.runCheck(() => { return this.runCheck(() => {
const result = const testRef = this.getObjectToTestReference();
this.getObjectToTestReference() === null || this.getObjectToTestReference() === undefined; const result = testRef === null || testRef === undefined;
if (!result) { if (!result) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not null or undefined` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not null or undefined`
); );
} }
}); });
} }
// Array checks
public toContain(itemArg: any) { public toContain(itemArg: any) {
return this.runCheck(() => { return this.runCheck(() => {
const result = const testRef = this.getObjectToTestReference();
this.getObjectToTestReference() instanceof Array && const result = Array.isArray(testRef) && testRef.includes(itemArg);
this.getObjectToTestReference().includes(itemArg);
if (!result) { if (!result) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not contain ${itemArg}` 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.`
); );
} }
}); });
@ -259,7 +392,10 @@ export class Assertion {
const result = typeof testObject === 'string' && testObject.startsWith(itemArg); const result = typeof testObject === 'string' && testObject.startsWith(itemArg);
if (!result) { if (!result) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not contain ${itemArg}` this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not start with ${itemArg}`
); );
} }
}); });
@ -271,20 +407,22 @@ export class Assertion {
const result = typeof testObject === 'string' && testObject.endsWith(itemArg); const result = typeof testObject === 'string' && testObject.endsWith(itemArg);
if (!result) { if (!result) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not contain ${itemArg}` this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not end with ${itemArg}`
); );
} }
}); });
} }
// ... previous code ...
public toBeOneOf(values: any[]) { public toBeOneOf(values: any[]) {
return this.runCheck(() => { return this.runCheck(() => {
const result = values.includes(this.getObjectToTestReference()); const result = values.includes(this.getObjectToTestReference());
if (!result) { if (!result) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not one of ${values}` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not one of ${values}`
); );
} }
}); });
@ -295,7 +433,10 @@ export class Assertion {
const obj = this.getObjectToTestReference(); const obj = this.getObjectToTestReference();
if (typeof obj.length !== 'number' || obj.length !== length) { if (typeof obj.length !== 'number' || obj.length !== length) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not have a length of ${length}` this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not have a length of ${length}`
); );
} }
}); });
@ -306,7 +447,10 @@ export class Assertion {
const difference = Math.abs(this.getObjectToTestReference() - value); const difference = Math.abs(this.getObjectToTestReference() - value);
if (difference > Math.pow(10, -precision) / 2) { if (difference > Math.pow(10, -precision) / 2) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not close to ${value} up to ${precision} decimal places` this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} is not close to ${value} up to ${precision} decimal places`
); );
} }
}); });
@ -321,7 +465,8 @@ export class Assertion {
thrown = true; thrown = true;
if (expectedError && !(e instanceof expectedError)) { if (expectedError && !(e instanceof expectedError)) {
throw new Error( throw new Error(
`Expected function to throw ${expectedError.name}, but it threw ${e.name}` this.failMessage ||
`Expected function to throw ${expectedError.name}, but it threw ${e.name}`
); );
} }
} }
@ -335,7 +480,8 @@ export class Assertion {
return this.runCheck(() => { return this.runCheck(() => {
if (!this.getObjectToTestReference()) { if (!this.getObjectToTestReference()) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not truthy` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not truthy`
); );
} }
}); });
@ -345,7 +491,8 @@ export class Assertion {
return this.runCheck(() => { return this.runCheck(() => {
if (this.getObjectToTestReference()) { if (this.getObjectToTestReference()) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not falsy` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not falsy`
); );
} }
}); });
@ -353,9 +500,12 @@ export class Assertion {
public toBeGreaterThanOrEqual(numberArg: number) { public toBeGreaterThanOrEqual(numberArg: number) {
return this.runCheck(() => { return this.runCheck(() => {
if (this.getObjectToTestReference() <= numberArg) { if (this.getObjectToTestReference() < numberArg) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not greater than or equal to ${numberArg}` this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} is not greater than or equal to ${numberArg}`
); );
} }
}); });
@ -363,9 +513,12 @@ export class Assertion {
public toBeLessThanOrEqual(numberArg: number) { public toBeLessThanOrEqual(numberArg: number) {
return this.runCheck(() => { return this.runCheck(() => {
if (this.getObjectToTestReference() >= numberArg) { if (this.getObjectToTestReference() > numberArg) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not less than or equal to ${numberArg}` this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} is not less than or equal to ${numberArg}`
); );
} }
}); });
@ -373,46 +526,14 @@ export class Assertion {
public toMatchObject(objectArg: object) { public toMatchObject(objectArg: object) {
return this.runCheck(() => { return this.runCheck(() => {
function deepEqual(obj1: any, obj2: any): boolean { // Implement a partial object match if needed.
// If both are of primitive types and are equal const matchResult = plugins.fastDeepEqual(this.getObjectToTestReference(), objectArg);
if (obj1 === obj2) { if (!matchResult) {
return true;
}
// If either of them is null or not an object
if (
typeof obj1 !== 'object' ||
obj1 === null ||
typeof obj2 !== 'object' ||
obj2 === null
) {
return false;
}
const keys1 = Object.keys(obj1);
const keys2 = Object.keys(obj2);
// If their properties' count doesn't match
if (keys1.length !== keys2.length) {
return false;
}
// Checking if every property in obj1 has a counterpart in obj2
for (const key of keys1) {
if (!keys2.includes(key)) {
return false;
}
if (!deepEqual(obj1[key], obj2[key])) {
return false;
}
}
return true;
}
const partialMatch = deepEqual(this.getObjectToTestReference(), objectArg); // Note: Implement a deep comparison function or use one from a library
if (!partialMatch) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not match the object ${objectArg}` this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not match the object ${JSON.stringify(objectArg)}`
); );
} }
}); });
@ -421,10 +542,18 @@ export class Assertion {
public toContainEqual(value: any) { public toContainEqual(value: any) {
return this.runCheck(() => { return this.runCheck(() => {
const arr = this.getObjectToTestReference(); const arr = this.getObjectToTestReference();
const found = arr.some((item: any) => plugins.fastDeepEqual(item, value)); // Assuming fastDeepEqual checks deep equality 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) { if (!found) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not contain the value ${value}` this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not contain the value ${JSON.stringify(value)}`
); );
} }
}); });
@ -434,7 +563,8 @@ export class Assertion {
return this.runCheck(() => { return this.runCheck(() => {
if (!Array.isArray(this.getObjectToTestReference())) { if (!Array.isArray(this.getObjectToTestReference())) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not an array` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not an array`
); );
} }
}); });
@ -442,9 +572,13 @@ export class Assertion {
public toInclude(substring: string) { public toInclude(substring: string) {
return this.runCheck(() => { return this.runCheck(() => {
if (!this.getObjectToTestReference().includes(substring)) { const testRef = this.getObjectToTestReference();
if (typeof testRef !== 'string' || !testRef.includes(substring)) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not include the substring ${substring}` this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not include the substring ${substring}`
); );
} }
}); });
@ -455,7 +589,10 @@ export class Assertion {
const obj = this.getObjectToTestReference(); const obj = this.getObjectToTestReference();
if (typeof obj.length !== 'number' || obj.length <= length) { if (typeof obj.length !== 'number' || obj.length <= length) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not have a length greater than ${length}` this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not have a length greater than ${length}`
); );
} }
}); });
@ -466,7 +603,10 @@ export class Assertion {
const obj = this.getObjectToTestReference(); const obj = this.getObjectToTestReference();
if (typeof obj.length !== 'number' || obj.length >= length) { if (typeof obj.length !== 'number' || obj.length >= length) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not have a length less than ${length}` this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not have a length less than ${length}`
); );
} }
}); });
@ -474,9 +614,11 @@ export class Assertion {
public toBeDate() { public toBeDate() {
return this.runCheck(() => { return this.runCheck(() => {
if (!(this.getObjectToTestReference() instanceof Date)) { const testRef = this.getObjectToTestReference();
if (!(testRef instanceof Date)) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not a date` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not a date`
); );
} }
}); });
@ -484,9 +626,11 @@ export class Assertion {
public toBeBeforeDate(date: Date) { public toBeBeforeDate(date: Date) {
return this.runCheck(() => { return this.runCheck(() => {
if (!(this.getObjectToTestReference() < date)) { const testRef = this.getObjectToTestReference();
if (!(testRef instanceof Date) || testRef >= date) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not before ${date}` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not before ${date}`
); );
} }
}); });
@ -494,16 +638,47 @@ export class Assertion {
public toBeAfterDate(date: Date) { public toBeAfterDate(date: Date) {
return this.runCheck(() => { return this.runCheck(() => {
if (!(this.getObjectToTestReference() > date)) { const testRef = this.getObjectToTestReference();
if (!(testRef instanceof Date) || testRef <= date) {
throw new Error( throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not after ${date}` this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not after ${date}`
); );
} }
}); });
} }
public customAssertion(
assertionFunction: (value: any) => boolean,
errorMessage: string
) {
return this.runCheck(() => {
if (!assertionFunction(this.getObjectToTestReference())) {
throw new Error(this.failMessage || errorMessage);
}
});
}
/**
* Drill into a property
*/
public property(propertyNameArg: string) { public property(propertyNameArg: string) {
this.propertyDrillDown.push(propertyNameArg); this.propertyDrillDown.push(propertyNameArg);
return this; return this;
} }
}
/**
* Drill into an array index
*/
public arrayItem(indexArg: number) {
// Save the number (instead of "[index]")
this.propertyDrillDown.push(indexArg);
return this;
}
public log() {
console.log(`this is the object to test:`);
console.log(JSON.stringify(this.getObjectToTestReference(), null, 2));
return this;
}
}

View File

@ -1,5 +1,5 @@
import * as smartdelay from '@pushrocks/smartdelay'; import * as smartdelay from '@push.rocks/smartdelay';
import * as smartpromise from '@pushrocks/smartpromise'; import * as smartpromise from '@push.rocks/smartpromise';
export { smartdelay, smartpromise }; export { smartdelay, smartpromise };

View File

@ -3,9 +3,12 @@
"experimentalDecorators": true, "experimentalDecorators": true,
"useDefineForClassFields": false, "useDefineForClassFields": false,
"target": "ES2022", "target": "ES2022",
"module": "ES2022", "module": "NodeNext",
"moduleResolution": "nodenext", "moduleResolution": "NodeNext",
"esModuleInterop": true, "esModuleInterop": true,
"verbatimModuleSyntax": true, "verbatimModuleSyntax": true
} },
"exclude": [
"dist_*/**/*.d.ts"
]
} }