Compare commits

...

46 Commits

Author SHA1 Message Date
6f1e37cf56 1.6.1 2025-03-04 12:32:00 +00:00
ed9a9b7f2c fix(build): Corrected package.json and workflow dependencies and resolved formatting issues in tests. 2025-03-04 12:32:00 +00:00
5801d34f18 1.6.0 2025-03-04 12:20:06 +00:00
f0ab180902 feat(assertion): Enhanced the assertion error messaging and added new test cases. 2025-03-04 12:20:06 +00:00
5f5628f647 1.5.0 2025-03-04 12:07:37 +00:00
e688207d23 feat(Assertion): Add toBeTypeOf assertion method 2025-03-04 12:07:37 +00:00
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
465e579298 1.0.17 2023-08-11 18:10:09 +02:00
f5f6e40fff fix(core): update 2023-08-11 18:10:08 +02:00
9d065a54e6 1.0.16 2023-08-11 18:08:51 +02:00
ee0a797424 fix(core): update 2023-08-11 18:08:50 +02:00
a234069cc8 switch to new org scheme 2023-07-10 02:49:04 +02:00
534c1e4215 1.0.15 2023-06-22 11:57:29 +02:00
931a713ae7 fix(core): update 2023-06-22 11:57:29 +02:00
d1be0d8ce2 1.0.14 2022-07-24 12:45:29 +02:00
3e5121171a fix(core): update 2022-07-24 12:45:29 +02:00
af12f068aa 1.0.13 2022-03-14 13:07:47 +01:00
b5d2be3ab8 fix(core): update 2022-03-14 13:07:46 +01:00
6fdd61b230 1.0.12 2022-02-15 16:13:49 +01:00
cdcf082ee0 fix(core): update 2022-02-15 16:13:48 +01:00
52b8a3f0d1 1.0.11 2022-02-02 08:02:27 +01:00
9213e7905f fix(core): update 2022-02-02 08:02:26 +01:00
56fb434f7d 1.0.10 2022-02-02 04:26:22 +01:00
b147de4713 fix(core): update 2022-02-02 04:26:22 +01:00
18 changed files with 11337 additions and 27857 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 @git.zone/tsdoc
npmci command tsdoc
continue-on-error: true

View File

@ -1,141 +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:
- npm install -g @shipzone/npmci
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
only:
- tags
tags:
- lossless
- docker
- notpriv
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --production --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=prod --production
tags:
- docker
allow_failure: true
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=dev
tags:
- docker
allow_failure: true
# ====================
# test stage
# ====================
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run 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 tslint typescript
- npmci npm prepare
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
stage: metadata
script:
- npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags:
- lossless
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

87
changelog.md Normal file
View File

@ -0,0 +1,87 @@
# Changelog
## 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
- Introduced a new assertion method `toBeTypeOf` allowing checks for expected data types.
- Updated devDependencies and dependencies to their latest versions.
## 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": "pushrocks", "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": "@pushrocks/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"
} }
} }

27557
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,28 +1,29 @@
{ {
"name": "@pushrocks/smartexpect", "name": "@push.rocks/smartexpect",
"version": "1.0.9", "version": "1.6.1",
"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",
"author": "Lossless GmbH", "author": "Lossless GmbH",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"test": "(tstest test/ --web)", "test": "(tstest test/ --web)",
"build": "(tsbuild --web)" "build": "(tsbuild tsfolders)",
"buildDocs": "tsdoc"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.25", "@git.zone/tsbuild": "^2.2.1",
"@gitzone/tsbundle": "^1.0.89", "@git.zone/tsbundle": "^2.2.5",
"@gitzone/tstest": "^1.0.44", "@git.zone/tsrun": "^1.3.3",
"@pushrocks/tapbundle": "^4.0.0", "@git.zone/tstest": "^1.0.96",
"@types/node": "^17.0.14", "@push.rocks/tapbundle": "^5.5.6",
"tslint": "^6.1.3", "@types/node": "^22.13.9"
"tslint-config-prettier": "^1.15.0"
}, },
"dependencies": { "dependencies": {
"@pushrocks/smartdelay": "^2.0.13", "@push.rocks/smartdelay": "^3.0.5",
"@pushrocks/smartpromise": "^3.1.6", "@push.rocks/smartpromise": "^4.2.3",
"fast-deep-equal": "^3.1.3" "fast-deep-equal": "^3.1.3"
}, },
"browserslist": [ "browserslist": [
@ -39,5 +40,27 @@
"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"
},
"pnpm": {
"onlyBuiltDependencies": [
"mongodb-memory-server"
] ]
} }
}

9923
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

1
readme.hints.md Normal file
View File

@ -0,0 +1 @@

279
readme.md
View File

@ -1,39 +1,262 @@
# @pushrocks/smartexpect # @push.rocks/smartexpect
manage expectations in code Manage expectations in code with precise, readable assertions
## 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)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](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';
```
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh) ### Synchronous Expectations
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com) You can employ `expect` to create synchronous assertions:
```typescript
import { expect } from '@push.rocks/smartexpect';
// Type assertions
expect('hello').toBeTypeofString();
expect(42).toBeTypeofNumber();
expect(true).toBeTypeofBoolean();
expect(() => {}).toBeTypeOf('function');
expect({}).toBeTypeOf('object');
// Negated assertions
expect(1).not.toBeTypeofString();
expect('string').not.toBeTypeofNumber();
// Equality assertion
expect('hithere').toEqual('hithere');
// Deep equality assertion
expect({ key: 'value' }).toEqual({ key: 'value' });
// Regular expression matching
expect('hithere').toMatch(/hi/);
```
### Asynchronous Expectations
For asynchronous operations, use `expectAsync` to return a promise:
```typescript
import { expectAsync } from '@push.rocks/smartexpect';
const asyncStringFetcher = async (): Promise<string> => {
return 'async string';
};
const asyncTest = async () => {
// Add a timeout to prevent hanging tests
await expectAsync(asyncStringFetcher()).timeout(5000).toBeTypeofString();
await expectAsync(asyncStringFetcher()).toEqual('async string');
};
asyncTest();
```
### Navigating Complex Objects
You can navigate complex objects using the `property()` and `arrayItem()` methods:
```typescript
const complexObject = {
users: [
{ id: 1, name: 'Alice', permissions: { admin: true } },
{ id: 2, name: 'Bob', permissions: { admin: false } }
]
};
// Navigate to a nested property
expect(complexObject)
.property('users')
.arrayItem(0)
.property('name')
.toEqual('Alice');
// Check nested permission
expect(complexObject)
.property('users')
.arrayItem(0)
.property('permissions')
.property('admin')
.toBeTrue();
```
### Advanced Assertions
#### Properties and Deep Properties
Assert the existence of properties and their values:
```typescript
const testObject = { level1: { level2: 'value' } };
// Property existence
expect(testObject).toHaveProperty('level1');
// Property with specific value
expect(testObject).toHaveProperty('level1.level2', 'value');
// Deep Property existence
expect(testObject).toHaveDeepProperty(['level1', 'level2']);
```
#### Conditions and Comparisons
Perform more intricate assertions:
```typescript
// Numeric comparisons
expect(5).toBeGreaterThan(3);
expect(3).toBeLessThan(5);
expect(5).toBeGreaterThanOrEqual(5);
expect(5).toBeLessThanOrEqual(5);
expect(0.1 + 0.2).toBeCloseTo(0.3, 10); // Floating point comparison with precision
// Truthiness checks
expect(true).toBeTrue();
expect(false).toBeFalse();
expect('non-empty').toBeTruthy();
expect(0).toBeFalsy();
// Null/Undefined checks
expect(null).toBeNull();
expect(undefined).toBeUndefined();
expect(null).toBeNullOrUndefined();
// Custom conditions
expect(7).customAssertion(value => value % 2 === 1, 'Value is not odd');
```
#### Arrays and Collections
Work seamlessly with arrays and collections:
```typescript
const testArray = [1, 2, 3];
// Array checks
expect(testArray).toBeArray();
expect(testArray).toHaveLength(3);
expect(testArray).toContain(2);
expect(testArray).toContainAll([1, 3]);
expect(testArray).toExclude(4);
expect([]).toBeEmptyArray();
expect(testArray).toHaveLengthGreaterThan(2);
expect(testArray).toHaveLengthLessThan(4);
// Deep equality in arrays
expect([{ id: 1 }, { id: 2 }]).toContainEqual({ id: 1 });
```
#### Strings
String-specific checks:
```typescript
expect('hello world').toStartWith('hello');
expect('hello world').toEndWith('world');
expect('hello world').toInclude('lo wo');
expect('options').toBeOneOf(['choices', 'options', 'alternatives']);
```
#### Functions and Exceptions
Test function behavior and exceptions:
```typescript
const throwingFn = () => { throw new Error('test error'); };
expect(throwingFn).toThrow();
expect(throwingFn).toThrow(Error);
const safeFn = () => 'result';
expect(safeFn).not.toThrow();
```
#### Date Assertions
Work with dates:
```typescript
const now = new Date();
const past = new Date(Date.now() - 10000);
const future = new Date(Date.now() + 10000);
expect(now).toBeDate();
expect(now).toBeAfterDate(past);
expect(now).toBeBeforeDate(future);
```
### Debugging Assertions
The `log()` method is useful for debugging complex assertions:
```typescript
expect(complexObject)
.property('users')
.log() // Logs the current value in the assertion chain
.arrayItem(0)
.log() // Logs the first user
.property('permissions')
.log() // Logs the permissions object
.property('admin')
.toBeTrue();
```
### Customizing Error Messages
You can provide custom error messages for more meaningful test failures:
```typescript
expect(user.age)
.setFailMessage('User age must be at least 18 for adult content')
.toBeGreaterThanOrEqual(18);
```
## Best Practices
- **Human-readable assertions**: The fluent API is designed to create tests that read like natural language sentences.
- **Precise error messages**: When tests fail, the error messages provide detailed information about what went wrong, including expected vs. actual values.
- **Property path navigation**: Use the property path methods to navigate complex objects without creating temporary variables.
- **Comprehensive testing**: Take advantage of the wide range of assertion methods to test various aspects of your code.
- **Debugging with log()**: Use the `log()` method to see intermediate values in the assertion chain during test development.
## License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
### Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.

218
test/test.both.ts Normal file
View File

@ -0,0 +1,218 @@
import { tap } from '@push.rocks/tapbundle';
import * as smartexpect from '../ts/index.js';
tap.test('basic type assertions', async () => {
// String type checks
smartexpect.expect('hello').toBeTypeofString();
smartexpect.expect(1).not.toBeTypeofString();
// Boolean type checks
smartexpect.expect(true).toBeTypeofBoolean();
smartexpect.expect(false).toBeTypeofBoolean();
smartexpect.expect(1).not.toBeTypeofBoolean();
// Number type checks
smartexpect.expect(42).toBeTypeofNumber();
smartexpect.expect(true).not.toBeTypeofNumber();
// Generic type checks with new method
smartexpect.expect(() => {}).toBeTypeOf('function');
smartexpect.expect(class Test {}).toBeTypeOf('function');
smartexpect.expect({}).toBeTypeOf('object');
smartexpect.expect(Symbol('test')).toBeTypeOf('symbol');
});
tap.test('async tests', async (toolsArg) => {
const deferred = toolsArg.defer();
toolsArg.delayFor(1000).then(() => {
deferred.resolve('hello');
});
await smartexpect.expectAsync(deferred.promise).timeout(2000).toBeTypeofString();
await smartexpect.expectAsync(deferred.promise).not.toBeTypeofBoolean();
// Test async timeout handling
const longOperation = toolsArg.defer();
toolsArg.delayFor(3000).then(() => {
longOperation.resolve('completed');
});
try {
await smartexpect.expectAsync(longOperation.promise).timeout(1000).toBeDefined();
throw new Error('Should have timed out');
} catch (err) {
// Expected timeout error
console.log('Successfully caught timeout:', err.message);
}
});
tap.test('equality and matching assertions', async () => {
// Basic equality
smartexpect.expect('hithere').toEqual('hithere');
smartexpect.expect('hithere').not.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).toEqual(obj2);
smartexpect.expect(obj1).not.toEqual(obj3);
// RegExp matching
smartexpect.expect('hithere').toMatch(/hi/);
smartexpect.expect('hithere').toMatch(/^hithere$/);
smartexpect.expect('hithere').not.toMatch(/ho/);
// String inclusion
smartexpect.expect('hithere').toInclude('hit');
smartexpect.expect('hithere').not.toInclude('missing');
// String start/end
smartexpect.expect('hithere').toStartWith('hi');
smartexpect.expect('hithere').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).toHaveProperty('topLevel');
smartexpect.expect(testObject).toHaveProperty('topLevel', 'hello');
smartexpect.expect(testObject).not.toHaveProperty('missing');
// Drill-down property navigation
smartexpect.expect(testObject).property('nested').toHaveProperty('prop', 42);
smartexpect
.expect(testObject)
.property('nested')
.property('deeplyNested')
.property('array')
.toBeArray();
// Deep property checks
smartexpect.expect(testObject).toHaveDeepProperty(['nested', 'deeplyNested', 'array']);
// Array item navigation
smartexpect
.expect(testObject)
.property('nested')
.property('deeplyNested')
.property('array')
.arrayItem(0)
.toEqual(1);
});
tap.test('numeric comparison assertions', async () => {
// Greater/less than
smartexpect.expect(4).toBeGreaterThan(3);
smartexpect.expect(4).toBeLessThan(5);
smartexpect.expect(4).toBeGreaterThanOrEqual(4);
smartexpect.expect(4).toBeLessThanOrEqual(4);
// Approximate equality
smartexpect.expect(0.1 + 0.2).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).toBeArray();
smartexpect.expect(testArray).toHaveLength(4);
// Content checks
smartexpect.expect(testArray).toContain('two');
smartexpect.expect(testArray).toContain(obj1);
smartexpect.expect(testArray).not.toContain(obj2);
// Array with equal items (not same reference)
smartexpect.expect([{ a: 1 }, { b: 2 }]).toContainEqual({ a: 1 });
// Multiple values
smartexpect.expect(testArray).toContainAll([1, 'two']);
smartexpect.expect(testArray).toExclude('missing');
// Empty array
smartexpect.expect([]).toBeEmptyArray();
// Length comparisons
smartexpect.expect(testArray).toHaveLengthGreaterThan(3);
smartexpect.expect(testArray).toHaveLengthLessThan(5);
});
tap.test('boolean assertions', async () => {
// True/False
smartexpect.expect(true).toBeTrue();
smartexpect.expect(false).toBeFalse();
// Truthy/Falsy
smartexpect.expect('something').toBeTruthy();
smartexpect.expect(0).toBeFalsy();
// Null/Undefined
smartexpect.expect(null).toBeNull();
smartexpect.expect(undefined).toBeUndefined();
smartexpect.expect(null).toBeNullOrUndefined();
smartexpect.expect(undefined).toBeNullOrUndefined();
});
tap.test('function assertions', async () => {
// Function that throws
const throwingFn = () => {
throw new Error('test error');
};
smartexpect.expect(throwingFn).toThrow();
smartexpect.expect(throwingFn).toThrow(Error);
// Function that doesn't throw
const nonThrowingFn = () => 'safe';
smartexpect.expect(nonThrowingFn).not.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).toBeDate();
smartexpect.expect(now).toBeAfterDate(past);
smartexpect.expect(now).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').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')
.toEqual('nested value');
});
export default tap.start();

View File

@ -1,39 +0,0 @@
import { tap } from '@pushrocks/tapbundle';
import * as smartexpect from '../ts/index';
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 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.start();

8
ts/00_commitinfo_data.ts Normal file
View File

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

View File

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

View File

@ -1,17 +1,89 @@
import * as plugins from './smartexpect.plugins'; import * as plugins from './smartexpect.plugins.js';
export type TExecutionType = 'sync' | 'async'; export type TExecutionType = 'sync' | 'async';
export class Assertion { export class Assertion {
executionMode: TExecutionType; executionMode: TExecutionType;
baseReference: any; baseReference: any;
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;
} }
private getObjectToTestReference() {
let returnObjectToTestReference = this.baseReference;
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];
}
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() { public get not() {
this.notSetting = true; this.notSetting = true;
return this; return this;
@ -22,6 +94,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) {
@ -34,7 +116,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 failed');
} }
} }
}; };
@ -42,16 +124,16 @@ export class Assertion {
if (this.executionMode === 'async') { if (this.executionMode === 'async') {
const done = plugins.smartpromise.defer(); const done = plugins.smartpromise.defer();
if (!(this.baseReference instanceof Promise)) { if (!(this.baseReference instanceof Promise)) {
done.reject(new Error(`${this.baseReference} is not of type promise.`)); done.reject(new Error(`Expected a Promise but received: ${this.formatValue(this.baseReference)}`));
} else { } else {
if (this.timeoutSetting) { if (this.timeoutSetting) {
plugins.smartdelay.delayFor(this.timeoutSetting).then(() => { plugins.smartdelay.delayFor(this.timeoutSetting).then(() => {
if (done.status === 'pending') { if (done.status === 'pending') {
done.reject(new Error(`${this.baseReference} timed out at ${this.timeoutSetting}!`)); done.reject(new Error(`Promise timed out after ${this.timeoutSetting}ms`));
} }
}); });
} }
this.baseReference.then((promiseResultArg) => { this.baseReference.then((promiseResultArg: any) => {
this.baseReference = promiseResultArg; this.baseReference = promiseResultArg;
done.resolve(runDirectOrNegated(checkFunction)); done.resolve(runDirectOrNegated(checkFunction));
}); });
@ -62,12 +144,22 @@ export class Assertion {
} }
} }
public toBeDefined() {
return this.runCheck(() => {
if (this.getObjectToTestReference() === undefined) {
throw new Error(
this.createErrorMessage('Expected value{path} to be defined, but got undefined')
);
}
});
}
public toBeTypeofString() { public toBeTypeofString() {
return this.runCheck(() => { return this.runCheck(() => {
if (typeof this.baseReference !== 'string') { const value = this.getObjectToTestReference();
if (typeof value !== 'string') {
throw new Error( throw new Error(
`Assertion failed: ${this.baseReference} is not of type string, but typeof ${typeof this this.createErrorMessage(`Expected value{path} to be of type string, but got ${typeof value}`)
.baseReference}`
); );
} }
}); });
@ -75,10 +167,10 @@ export class Assertion {
public toBeTypeofNumber() { public toBeTypeofNumber() {
return this.runCheck(() => { return this.runCheck(() => {
if (typeof this.baseReference !== 'number') { const value = this.getObjectToTestReference();
if (typeof value !== 'number') {
throw new Error( throw new Error(
`Assertion failed: ${this.baseReference} is not of type string, but typeof ${typeof this this.createErrorMessage(`Expected value{path} to be of type number, but got ${typeof value}`)
.baseReference}`
); );
} }
}); });
@ -86,10 +178,22 @@ export class Assertion {
public toBeTypeofBoolean() { public toBeTypeofBoolean() {
return this.runCheck(() => { return this.runCheck(() => {
if (typeof this.baseReference !== 'boolean') { const value = this.getObjectToTestReference();
if (typeof value !== 'boolean') {
throw new Error( throw new Error(
`Assertion failed: ${this.baseReference} is not of type string, but typeof ${typeof this this.createErrorMessage(`Expected value{path} to be of type boolean, but got ${typeof value}`)
.baseReference}` );
}
});
}
public toBeTypeOf(expectedType: string) {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
const actualType = typeof value;
if (actualType !== expectedType) {
throw new Error(
this.createErrorMessage(`Expected value{path} to be of type ${expectedType}, but got ${actualType}`)
); );
} }
}); });
@ -97,103 +201,536 @@ export class Assertion {
public toEqual(comparisonObject: any) { public toEqual(comparisonObject: any) {
return this.runCheck(() => { return this.runCheck(() => {
const result = plugins.fastDeepEqual(this.baseReference, comparisonObject); const value = this.getObjectToTestReference();
const result = plugins.fastDeepEqual(value, comparisonObject);
if (!result) { if (!result) {
throw new Error(`${this.baseReference} does not equal ${comparisonObject}`); throw new Error(
this.createErrorMessage(`Expected value{path} to equal ${this.formatValue(comparisonObject)}`)
);
}
});
}
public toMatch(comparisonObject: RegExp) {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
const result = comparisonObject.test(value);
if (!result) {
throw new Error(
this.createErrorMessage(`Expected value{path} to match regex ${comparisonObject}`)
);
} }
}); });
} }
public toBeTrue() { public toBeTrue() {
return this.runCheck(() => { return this.runCheck(() => {
const result = typeof this.baseReference === 'boolean' && this.baseReference === true; const value = this.getObjectToTestReference();
const result = typeof value === 'boolean' && value === true;
if (!result) { if (!result) {
throw new Error(`${this.baseReference} is not true or not of type boolean`); throw new Error(
this.createErrorMessage(`Expected value{path} to be true, but got ${this.formatValue(value)}`)
);
} }
}); });
} }
public toBeFalse() { public toBeFalse() {
return this.runCheck(() => { return this.runCheck(() => {
const result = typeof this.baseReference === 'boolean' && this.baseReference === false; const value = this.getObjectToTestReference();
const result = typeof value === 'boolean' && value === false;
if (!result) { if (!result) {
throw new Error(`${this.baseReference} is not false or not of type boolean`); throw new Error(
this.createErrorMessage(`Expected value{path} to be false, but got ${this.formatValue(value)}`)
);
} }
}); });
} }
public toBeInstanceOf(classArg: any) { public toBeInstanceOf(classArg: any) {
return this.runCheck(() => { return this.runCheck(() => {
const result = this.baseReference instanceof classArg; const value = this.getObjectToTestReference();
const result = value instanceof classArg;
if (!result) { if (!result) {
throw new Error(`${this.baseReference} is not an instance of ${classArg}`); throw new Error(
this.createErrorMessage(`Expected value{path} to be an instance of ${classArg.name || 'provided class'}`)
);
} }
}); });
} }
public toHaveProperty(propertyArg: string) { public toHaveProperty(propertyArg: string, equalsArg?: any) {
return this.runCheck(() => { return this.runCheck(() => {
const result = !!this.baseReference[propertyArg]; const obj = this.getObjectToTestReference();
if (!result) { if (!obj || !(propertyArg in obj)) {
throw new Error(`${this.baseReference} does not have property ${propertyArg}`); throw new Error(
this.createErrorMessage(`Expected value{path} to have property '${propertyArg}'`)
);
}
if (equalsArg !== undefined) {
if (obj[propertyArg] !== equalsArg) {
throw new Error(
this.createErrorMessage(
`Expected property '${propertyArg}' of value{path} to equal ${this.formatValue(equalsArg)}, but got ${this.formatValue(obj[propertyArg])}`
)
);
}
}
});
}
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.createErrorMessage(`Expected value{path} to have property at path '${currentPath}'`)
);
}
obj = obj[property];
} }
}); });
} }
public toBeGreaterThan(numberArg: number) { public toBeGreaterThan(numberArg: number) {
return this.runCheck(() => { return this.runCheck(() => {
const result = this.baseReference > numberArg; const value = this.getObjectToTestReference();
const result = value > numberArg;
if (!result) { if (!result) {
throw new Error(`${this.baseReference} is not greater than ${numberArg}`); throw new Error(
this.createErrorMessage(`Expected value{path} to be greater than ${numberArg}, but got ${this.formatValue(value)}`)
);
} }
}); });
} }
public toBeLessThan(numberArg: number) { public toBeLessThan(numberArg: number) {
return this.runCheck(() => { return this.runCheck(() => {
const result = this.baseReference < numberArg; const value = this.getObjectToTestReference();
const result = value < numberArg;
if (!result) { if (!result) {
throw new Error(`${this.baseReference} is not less than ${numberArg}`); throw new Error(
this.createErrorMessage(`Expected value{path} to be less than ${numberArg}, but got ${this.formatValue(value)}`)
);
} }
}); });
} }
public toBeNull() { public toBeNull() {
return this.runCheck(() => { return this.runCheck(() => {
const result = this.baseReference === null; const value = this.getObjectToTestReference();
const result = value === null;
if (!result) { if (!result) {
throw new Error(`${this.baseReference} is not null`); throw new Error(
this.createErrorMessage(`Expected value{path} to be null, but got ${this.formatValue(value)}`)
);
} }
}); });
} }
public toBeUndefined() { public toBeUndefined() {
return this.runCheck(() => { return this.runCheck(() => {
const result = this.baseReference === undefined; const value = this.getObjectToTestReference();
const result = value === undefined;
if (!result) { if (!result) {
throw new Error(`${this.baseReference} is not undefined`); throw new Error(
this.createErrorMessage(`Expected value{path} to be undefined, but got ${this.formatValue(value)}`)
);
} }
}); });
} }
public toBeNullOrUndefined() { public toBeNullOrUndefined() {
return this.runCheck(() => { return this.runCheck(() => {
const result = this.baseReference === null || this.baseReference === undefined; const value = this.getObjectToTestReference();
const result = value === null || value === undefined;
if (!result) { if (!result) {
throw new Error(`${this.baseReference} is not null or undefined`); throw new Error(
this.createErrorMessage(`Expected value{path} to be null or undefined, but got ${this.formatValue(value)}`)
);
} }
}); });
} }
// Array checks
public toContain(itemArg: any) { public toContain(itemArg: any) {
return this.runCheck(() => { return this.runCheck(() => {
const result = this.baseReference instanceof Array && this.baseReference.find(itemArg2 => { const value = this.getObjectToTestReference();
itemArg === itemArg2; const result = Array.isArray(value) && value.includes(itemArg);
})
if (!result) { if (!result) {
throw new Error(`${this.baseReference} is not contain ${itemArg}`); throw new Error(
this.createErrorMessage(`Expected array{path} to contain ${this.formatValue(itemArg)}`)
);
} }
}); });
}
public toBeEmptyArray() {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
if (!Array.isArray(value)) {
throw new Error(
this.createErrorMessage(`Expected value{path} to be an array, but got ${typeof value}`)
);
}
if (value.length !== 0) {
throw new Error(
this.createErrorMessage(`Expected array{path} to be empty, but it has ${value.length} elements`)
);
}
});
}
public toContainAll(values: any[]) {
return this.runCheck(() => {
const arr = this.getObjectToTestReference();
if (!Array.isArray(arr)) {
throw new Error(
this.createErrorMessage(`Expected value{path} to be an array, but got ${typeof arr}`)
);
}
const missing = values.filter(v => !arr.includes(v));
if (missing.length > 0) {
throw new Error(
this.createErrorMessage(`Expected array{path} to contain all values ${this.formatValue(values)}, but missing: ${this.formatValue(missing)}`)
);
}
});
}
public toExclude(value: any) {
return this.runCheck(() => {
const arr = this.getObjectToTestReference();
if (!Array.isArray(arr)) {
throw new Error(
this.createErrorMessage(`Expected value{path} to be an array, but got ${typeof arr}`)
);
}
if (arr.includes(value)) {
throw new Error(
this.createErrorMessage(`Expected array{path} to exclude ${this.formatValue(value)}, but it was found`)
);
}
});
}
public toStartWith(itemArg: any) {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
const result = typeof value === 'string' && value.startsWith(itemArg);
if (!result) {
throw new Error(
this.createErrorMessage(`Expected string{path} to start with "${itemArg}", but got "${value}"`)
);
}
});
}
public toEndWith(itemArg: any) {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
const result = typeof value === 'string' && value.endsWith(itemArg);
if (!result) {
throw new Error(
this.createErrorMessage(`Expected string{path} to end with "${itemArg}", but got "${value}"`)
);
}
});
}
public toBeOneOf(values: any[]) {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
const result = values.includes(value);
if (!result) {
throw new Error(
this.createErrorMessage(`Expected value{path} to be one of ${this.formatValue(values)}, but got ${this.formatValue(value)}`)
);
}
});
}
public toHaveLength(length: number) {
return this.runCheck(() => {
const obj = this.getObjectToTestReference();
if (typeof obj.length !== 'number') {
throw new Error(
this.createErrorMessage(`Expected value{path} to have a length property, but it doesn't`)
);
}
if (obj.length !== length) {
throw new Error(
this.createErrorMessage(`Expected value{path} to have length ${length}, but got length ${obj.length}`)
);
}
});
}
public toBeCloseTo(value: number, precision = 2) {
return this.runCheck(() => {
const actual = this.getObjectToTestReference();
const difference = Math.abs(actual - value);
const epsilon = Math.pow(10, -precision) / 2;
if (difference > epsilon) {
throw new Error(
this.createErrorMessage(`Expected value{path} to be close to ${value} (within ${epsilon}), but the difference was ${difference}`)
);
}
});
}
public toThrow(expectedError?: any) {
return this.runCheck(() => {
const fn = this.getObjectToTestReference();
if (typeof fn !== 'function') {
throw new Error(
this.createErrorMessage(`Expected value{path} to be a function, but got ${typeof fn}`)
);
}
let thrown = false;
let error: any;
try {
fn();
} catch (e) {
thrown = true;
error = e;
if (expectedError && !(e instanceof expectedError)) {
throw new Error(
this.createErrorMessage(`Expected function{path} to throw ${expectedError.name}, but it threw ${e.constructor.name}`)
);
}
}
if (!thrown) {
throw new Error(
this.createErrorMessage(`Expected function{path} to throw, but it didn't throw any error`)
);
}
});
}
public toBeTruthy() {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
if (!value) {
throw new Error(
this.createErrorMessage(`Expected value{path} to be truthy, but got ${this.formatValue(value)}`)
);
}
});
}
public toBeFalsy() {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
if (value) {
throw new Error(
this.createErrorMessage(`Expected value{path} to be falsy, but got ${this.formatValue(value)}`)
);
}
});
}
public toBeGreaterThanOrEqual(numberArg: number) {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
if (value < numberArg) {
throw new Error(
this.createErrorMessage(`Expected value{path} to be greater than or equal to ${numberArg}, but got ${value}`)
);
}
});
}
public toBeLessThanOrEqual(numberArg: number) {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
if (value > numberArg) {
throw new Error(
this.createErrorMessage(`Expected value{path} to be less than or equal to ${numberArg}, but got ${value}`)
);
}
});
}
public toMatchObject(objectArg: object) {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
const matchResult = plugins.fastDeepEqual(value, objectArg);
if (!matchResult) {
throw new Error(
this.createErrorMessage(`Expected value{path} to match ${this.formatValue(objectArg)}`)
);
}
});
}
public toContainEqual(value: any) {
return this.runCheck(() => {
const arr = this.getObjectToTestReference();
if (!Array.isArray(arr)) {
throw new Error(
this.createErrorMessage(`Expected value{path} to be an array, but got ${typeof arr}`)
);
}
const found = arr.some((item: any) => plugins.fastDeepEqual(item, value));
if (!found) {
throw new Error(
this.createErrorMessage(`Expected array{path} to contain an item equal to ${this.formatValue(value)}`)
);
}
});
}
public toBeArray() {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
if (!Array.isArray(value)) {
throw new Error(
this.createErrorMessage(`Expected value{path} to be an array, but got ${typeof value}`)
);
}
});
}
public toInclude(substring: string) {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
if (typeof value !== 'string') {
throw new Error(
this.createErrorMessage(`Expected value{path} to be a string, but got ${typeof value}`)
);
}
if (!value.includes(substring)) {
throw new Error(
this.createErrorMessage(`Expected string{path} to include "${substring}", but it doesn't`)
);
}
});
}
public toHaveLengthGreaterThan(length: number) {
return this.runCheck(() => {
const obj = this.getObjectToTestReference();
if (typeof obj.length !== 'number') {
throw new Error(
this.createErrorMessage(`Expected value{path} to have a length property, but it doesn't`)
);
}
if (obj.length <= length) {
throw new Error(
this.createErrorMessage(`Expected value{path} to have length greater than ${length}, but got length ${obj.length}`)
);
}
});
}
public toHaveLengthLessThan(length: number) {
return this.runCheck(() => {
const obj = this.getObjectToTestReference();
if (typeof obj.length !== 'number') {
throw new Error(
this.createErrorMessage(`Expected value{path} to have a length property, but it doesn't`)
);
}
if (obj.length >= length) {
throw new Error(
this.createErrorMessage(`Expected value{path} to have length less than ${length}, but got length ${obj.length}`)
);
}
});
}
public toBeDate() {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
if (!(value instanceof Date)) {
throw new Error(
this.createErrorMessage(`Expected value{path} to be a Date, but got ${value.constructor ? value.constructor.name : typeof value}`)
);
}
});
}
public toBeBeforeDate(date: Date) {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
if (!(value instanceof Date)) {
throw new Error(
this.createErrorMessage(`Expected value{path} to be a Date, but got ${value.constructor ? value.constructor.name : typeof value}`)
);
}
if (value >= date) {
throw new Error(
this.createErrorMessage(`Expected date{path} to be before ${date.toISOString()}, but got ${value.toISOString()}`)
);
}
});
}
public toBeAfterDate(date: Date) {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
if (!(value instanceof Date)) {
throw new Error(
this.createErrorMessage(`Expected value{path} to be a Date, but got ${value.constructor ? value.constructor.name : typeof value}`)
);
}
if (value <= date) {
throw new Error(
this.createErrorMessage(`Expected date{path} to be after ${date.toISOString()}, but got ${value.toISOString()}`)
);
}
});
}
public customAssertion(
assertionFunction: (value: any) => boolean,
errorMessage: string
) {
return this.runCheck(() => {
const value = this.getObjectToTestReference();
if (!assertionFunction(value)) {
throw new Error(this.failMessage || errorMessage);
}
});
}
/**
* Drill into a property
*/
public property(propertyNameArg: string) {
this.propertyDrillDown.push(propertyNameArg);
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(`Current value:`);
console.log(JSON.stringify(this.getObjectToTestReference(), null, 2));
console.log(`Path: ${this.formatDrillDown() || '(root)'}`);
return this;
} }
} }

View File

@ -1,14 +1,9 @@
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 { export { smartdelay, smartpromise };
smartdelay,
smartpromise
}
// third party scope // third party scope
import fastDeepEqual from 'fast-deep-equal'; import fastDeepEqual from 'fast-deep-equal';
export { export { fastDeepEqual };
fastDeepEqual,
}

15
tsconfig.json Normal file
View File

@ -0,0 +1,15 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"verbatimModuleSyntax": true
},
"exclude": [
"dist_*/**/*.d.ts"
]
}

View File

@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}