Compare commits

..

26 Commits

Author SHA1 Message Date
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
17 changed files with 6931 additions and 27813 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,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

47
changelog.md Normal file
View File

@ -0,0 +1,47 @@
# Changelog
## 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": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "pushrocks",
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartexpect",
"description": "manage expectations in code",
"npmPackagename": "@pushrocks/smartexpect",
"description": "A testing library to manage expectations in code, offering both synchronous and asynchronous assertion methods.",
"npmPackagename": "@push.rocks/smartexpect",
"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": {
"npmGlobalTools": [],
"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",
"version": "1.0.13",
"name": "@push.rocks/smartexpect",
"version": "1.2.0",
"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",
"typings": "dist_ts/index.d.ts",
"type": "module",
"author": "Lossless GmbH",
"license": "MIT",
"scripts": {
"test": "(tstest test/ --web)",
"build": "(tsbuild --web)"
"build": "(tsbuild --web)",
"buildDocs": "tsdoc"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.1.25",
"@gitzone/tsbundle": "^1.0.89",
"@gitzone/tstest": "^1.0.44",
"@pushrocks/tapbundle": "^4.0.0",
"@types/node": "^17.0.14",
"tslint": "^6.1.3",
"tslint-config-prettier": "^1.15.0"
"@gitzone/tsbuild": "^2.1.66",
"@gitzone/tsbundle": "^2.0.8",
"@gitzone/tsrun": "^1.2.44",
"@gitzone/tstest": "^1.0.77",
"@push.rocks/tapbundle": "^5.0.23",
"@types/node": "^22.4.0"
},
"dependencies": {
"@pushrocks/smartdelay": "^2.0.13",
"@pushrocks/smartpromise": "^3.1.6",
"@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/smartpromise": "^4.0.4",
"fast-deep-equal": "^3.1.3"
},
"browserslist": [
@ -39,5 +40,22 @@
"cli.js",
"npmextra.json",
"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"
}
}

6100
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 @@

159
readme.md
View File

@ -1,39 +1,144 @@
# @pushrocks/smartexpect
# @push.rocks/smartexpect
manage expectations in code
## Availabililty and Links
* [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/)
## Install
## Status for master
To install `@push.rocks/smartexpect`, use the following command in your terminal:
Status Category | Status Badge
-- | --
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)
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)
```bash
npm install @push.rocks/smartexpect --save
```
This will add `@push.rocks/smartexpect` to your project's dependencies. Make sure you're inside your project directory before running this command.
## Usage
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)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
### Synchronous Expectations
[![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';
// 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,5 +1,5 @@
import { tap } from '@pushrocks/tapbundle';
import * as smartexpect from '../ts/index';
import { tap } from '@push.rocks/tapbundle';
import * as smartexpect from '../ts/index.js';
tap.test('sync tests', async () => {
smartexpect.expect('hello').toBeTypeofString();
@ -20,11 +20,16 @@ tap.test('async tests', async (toolsArg) => {
tap.test('should check equality', async () => {
smartexpect.expect('hithere').toEqual('hithere');
smartexpect.expect('hithere').not.toEqual('hithere2');
})
});
tap.test('should check for regexp matching', async () => {
smartexpect.expect('hithere').toMatch(/hi/);
smartexpect.expect('hithere').not.toMatch(/ho/);
});
tap.test('should correctly state property presence', async () => {
const testObject = {
aprop: 'hello'
aprop: 'hello',
};
smartexpect.expect(testObject).toHaveProperty('aprop');
@ -34,14 +39,14 @@ tap.test('should correctly state property presence', async () => {
tap.test('should be greater than', async () => {
smartexpect.expect(4).toBeGreaterThan(3);
smartexpect.expect(4).toBeLessThan(5);
})
});
tap.test('should correctly determine toContain', async () => {
const hello = {
socool: 'yes'
socool: 'yes',
};
const testArray = [hello];
smartexpect.expect(testArray).toContain(hello);
})
});
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.2.0',
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';
import { Assertion } from './smartexpect.classes.assertion.js';
export const expect = (baseArg: any) => {
const assertion = new Assertion(baseArg, 'sync');
return assertion;
}
};
export const expectAsync = (baseArg: any) => {
const assertion = new Assertion(baseArg, 'async');
return assertion;
}
};

View File

@ -1,4 +1,4 @@
import * as plugins from './smartexpect.plugins';
import * as plugins from './smartexpect.plugins.js';
export type TExecutionType = 'sync' | 'async';
@ -31,6 +31,18 @@ export class Assertion {
return this;
}
private failMessage: string;
public withFailMessage(failMessageArg: string) {
this.failMessage = failMessageArg;
return this;
}
private successMessage: string;
public withSuccessMessage(successMessageArg: string) {
this.successMessage = successMessageArg;
return this;
}
private runCheck(checkFunction: () => any) {
const runDirectOrNegated = (checkFunction: () => any) => {
if (!this.notSetting) {
@ -43,7 +55,7 @@ export class Assertion {
isOk = true;
}
if (!isOk) {
throw new Error('Negated assertion is not ok!');
throw new Error(this.failMessage || 'Negated assertion is not ok!');
}
}
};
@ -71,12 +83,29 @@ export class Assertion {
}
}
/**
* checks if the given object is defined
*/
public toBeDefined() {
return this.runCheck(() => {
if (this.getObjectToTestReference() === undefined) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not defined`
);
}
});
}
/**
* checks if the given object is not defined
*/
public toBeTypeofString() {
return this.runCheck(() => {
if (typeof this.getObjectToTestReference() !== 'string') {
throw new Error(
`Assertion failed: ${this.baseReference} with drill down ${this.propertyDrillDown} is not of type string, but typeof ${typeof this
.baseReference}`
this.failMessage || `Assertion failed: ${this.baseReference} with drill down ${
this.propertyDrillDown
} is not of type string, but typeof ${typeof this.baseReference}`
);
}
});
@ -86,8 +115,9 @@ export class Assertion {
return this.runCheck(() => {
if (typeof this.getObjectToTestReference() !== 'number') {
throw new Error(
`Assertion failed: ${this.baseReference} with drill down ${this.propertyDrillDown} is not of type string, but typeof ${typeof this
.baseReference}`
this.failMessage || `Assertion failed: ${this.baseReference} with drill down ${
this.propertyDrillDown
} is not of type string, but typeof ${typeof this.baseReference}`
);
}
});
@ -97,8 +127,9 @@ export class Assertion {
return this.runCheck(() => {
if (typeof this.getObjectToTestReference() !== 'boolean') {
throw new Error(
`Assertion failed: ${this.baseReference} with drill down ${this.propertyDrillDown} is not of type string, but typeof ${typeof this
.baseReference}`
this.failMessage || `Assertion failed: ${this.baseReference} with drill down ${
this.propertyDrillDown
} is not of type string, but typeof ${typeof this.baseReference}`
);
}
});
@ -108,25 +139,46 @@ export class Assertion {
return this.runCheck(() => {
const result = plugins.fastDeepEqual(this.getObjectToTestReference(), comparisonObject);
if (!result) {
throw new Error(`${this.baseReference} with drill down ${this.propertyDrillDown} does not equal ${comparisonObject}`);
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} does not equal ${comparisonObject}`
);
}
});
}
public toMatch(comparisonObject: RegExp) {
return this.runCheck(() => {
const result = comparisonObject.test(this.getObjectToTestReference());
if (!result) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} does not equal ${comparisonObject}`
);
}
});
}
public toBeTrue() {
return this.runCheck(() => {
const result = typeof this.getObjectToTestReference() === 'boolean' && this.getObjectToTestReference() === true;
const result =
typeof this.getObjectToTestReference() === 'boolean' &&
this.getObjectToTestReference() === true;
if (!result) {
throw new Error(`${this.baseReference} with drill down ${this.propertyDrillDown} is not true or not of type boolean`);
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not true or not of type boolean`
);
}
});
}
public toBeFalse() {
return this.runCheck(() => {
const result = typeof this.getObjectToTestReference() === 'boolean' && this.getObjectToTestReference() === false;
const result =
typeof this.getObjectToTestReference() === 'boolean' &&
this.getObjectToTestReference() === false;
if (!result) {
throw new Error(`${this.baseReference} with drill down ${this.propertyDrillDown} is not false or not of type boolean`);
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not false or not of type boolean`
);
}
});
}
@ -135,16 +187,47 @@ export class Assertion {
return this.runCheck(() => {
const result = this.getObjectToTestReference() instanceof classArg;
if (!result) {
throw new Error(`${this.baseReference} with drill down ${this.propertyDrillDown} is not an instance of ${classArg}`);
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not an instance of ${classArg}`
);
}
});
}
public toHaveProperty(propertyArg: string) {
public toHaveProperty(propertyArg: string, equalsArg?: any) {
return this.runCheck(() => {
const result = !!this.getObjectToTestReference()[propertyArg];
if (!result) {
throw new Error(`${this.baseReference} with drill down ${this.propertyDrillDown} does not have property ${propertyArg}`);
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} does not have property ${propertyArg}`
);
}
if (equalsArg) {
if (result !== equalsArg) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} does have property ${propertyArg}, but it does not equal ${equalsArg}`
);
}
}
});
}
public toHaveDeepProperty(properties: string[]) {
return this.runCheck(() => {
let obj = this.getObjectToTestReference();
let currentPath = '';
for (const property of properties) {
if (currentPath) {
currentPath += `.${property}`;
} else {
currentPath = property;
}
if (!obj || !(property in obj)) {
throw new Error(this.failMessage || `Missing property at path "${currentPath}" in ${this.baseReference}`);
}
obj = obj[property];
}
});
}
@ -153,7 +236,9 @@ export class Assertion {
return this.runCheck(() => {
const result = this.getObjectToTestReference() > numberArg;
if (!result) {
throw new Error(`${this.baseReference} with drill down ${this.propertyDrillDown} is not greater than ${numberArg}`);
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not greater than ${numberArg}`
);
}
});
}
@ -162,7 +247,9 @@ export class Assertion {
return this.runCheck(() => {
const result = this.getObjectToTestReference() < numberArg;
if (!result) {
throw new Error(`${this.baseReference} with drill down ${this.propertyDrillDown} is not less than ${numberArg}`);
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not less than ${numberArg}`
);
}
});
}
@ -171,7 +258,9 @@ export class Assertion {
return this.runCheck(() => {
const result = this.getObjectToTestReference() === null;
if (!result) {
throw new Error(`${this.baseReference} with drill down ${this.propertyDrillDown} is not null`);
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not null`
);
}
});
}
@ -180,27 +269,77 @@ export class Assertion {
return this.runCheck(() => {
const result = this.getObjectToTestReference() === undefined;
if (!result) {
throw new Error(`${this.baseReference} with drill down ${this.propertyDrillDown} is not undefined`);
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not undefined`
);
}
});
}
public toBeNullOrUndefined() {
return this.runCheck(() => {
const result = this.getObjectToTestReference() === null || this.getObjectToTestReference() === undefined;
const result =
this.getObjectToTestReference() === null || this.getObjectToTestReference() === undefined;
if (!result) {
throw new Error(`${this.baseReference} with drill down ${this.propertyDrillDown} is not null or undefined`);
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not null or undefined`
);
}
});
}
// Array
public toContain(itemArg: any) {
return this.runCheck(() => {
const result =
this.getObjectToTestReference() instanceof Array &&
this.getObjectToTestReference().includes(itemArg);
if (!result) {
throw new Error(`${this.baseReference} with drill down ${this.propertyDrillDown} is not contain ${itemArg}`);
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is 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} 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} to be an array.`);
}
if (arrayRef.includes(value)) {
throw new Error(
this.failMessage || `Expected ${this.baseReference} to exclude value "${value}", but it included it.`
);
}
});
}
@ -208,11 +347,11 @@ export class Assertion {
public toStartWith(itemArg: any) {
return this.runCheck(() => {
const testObject = this.getObjectToTestReference();
const result =
typeof testObject === 'string' &&
testObject.startsWith(itemArg);
const result = typeof testObject === 'string' && testObject.startsWith(itemArg);
if (!result) {
throw new Error(`${this.baseReference} with drill down ${this.propertyDrillDown} is not contain ${itemArg}`);
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not contain ${itemArg}`
);
}
});
}
@ -220,11 +359,208 @@ export class Assertion {
public toEndWith(itemArg: any) {
return this.runCheck(() => {
const testObject = this.getObjectToTestReference();
const result =
typeof testObject === 'string' &&
testObject.endsWith(itemArg);
const result = typeof testObject === 'string' && testObject.endsWith(itemArg);
if (!result) {
throw new Error(`${this.baseReference} with drill down ${this.propertyDrillDown} is not contain ${itemArg}`);
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not contain ${itemArg}`
);
}
});
}
// ... previous code ...
public toBeOneOf(values: any[]) {
return this.runCheck(() => {
const result = values.includes(this.getObjectToTestReference());
if (!result) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not one of ${values}`
);
}
});
}
public toHaveLength(length: number) {
return this.runCheck(() => {
const obj = this.getObjectToTestReference();
if (typeof obj.length !== 'number' || obj.length !== length) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} does not have a length of ${length}`
);
}
});
}
public toBeCloseTo(value: number, precision = 2) {
return this.runCheck(() => {
const difference = Math.abs(this.getObjectToTestReference() - value);
if (difference > Math.pow(10, -precision) / 2) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not close to ${value} up to ${precision} decimal places`
);
}
});
}
public toThrow(expectedError?: any) {
return this.runCheck(() => {
let thrown = false;
try {
this.getObjectToTestReference()();
} catch (e) {
thrown = true;
if (expectedError && !(e instanceof expectedError)) {
throw new Error(
this.failMessage || `Expected function to throw ${expectedError.name}, but it threw ${e.name}`
);
}
}
if (!thrown) {
throw new Error(`Expected function to throw, but it didn't.`);
}
});
}
public toBeTruthy() {
return this.runCheck(() => {
if (!this.getObjectToTestReference()) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not truthy`
);
}
});
}
public toBeFalsy() {
return this.runCheck(() => {
if (this.getObjectToTestReference()) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not falsy`
);
}
});
}
public toBeGreaterThanOrEqual(numberArg: number) {
return this.runCheck(() => {
if (this.getObjectToTestReference() <= numberArg) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not greater than or equal to ${numberArg}`
);
}
});
}
public toBeLessThanOrEqual(numberArg: number) {
return this.runCheck(() => {
if (this.getObjectToTestReference() >= numberArg) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not less than or equal to ${numberArg}`
);
}
});
}
public toMatchObject(objectArg: object) {
return this.runCheck(() => {
const partialMatch = plugins.fastDeepEqual(this.getObjectToTestReference(), objectArg); // Note: Implement a deep comparison function or use one from a library
if (!partialMatch) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} does not match the object ${objectArg}`
);
}
});
}
public toContainEqual(value: any) {
return this.runCheck(() => {
const arr = this.getObjectToTestReference();
const found = arr.some((item: any) => plugins.fastDeepEqual(item, value)); // Assuming fastDeepEqual checks deep equality
if (!found) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not contain the value ${value}`
);
}
});
}
public toBeArray() {
return this.runCheck(() => {
if (!Array.isArray(this.getObjectToTestReference())) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not an array`
);
}
});
}
public toInclude(substring: string) {
return this.runCheck(() => {
if (!this.getObjectToTestReference().includes(substring)) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} does not include the substring ${substring}`
);
}
});
}
public toHaveLengthGreaterThan(length: number) {
return this.runCheck(() => {
const obj = this.getObjectToTestReference();
if (typeof obj.length !== 'number' || obj.length <= length) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} does not have a length greater than ${length}`
);
}
});
}
public toHaveLengthLessThan(length: number) {
return this.runCheck(() => {
const obj = this.getObjectToTestReference();
if (typeof obj.length !== 'number' || obj.length >= length) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} does not have a length less than ${length}`
);
}
});
}
public toBeDate() {
return this.runCheck(() => {
if (!(this.getObjectToTestReference() instanceof Date)) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not a date`
);
}
});
}
public toBeBeforeDate(date: Date) {
return this.runCheck(() => {
if (!(this.getObjectToTestReference() < date)) {
throw new Error(
this.failMessage || `${this.baseReference} with drill down ${this.propertyDrillDown} is not before ${date}`
);
}
});
}
public toBeAfterDate(date: Date) {
return this.runCheck(() => {
if (!(this.getObjectToTestReference() > date)) {
throw new Error(
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);
}
});
}

View File

@ -1,14 +1,9 @@
import * as smartdelay from '@pushrocks/smartdelay';
import * as smartpromise from '@pushrocks/smartpromise';
import * as smartdelay from '@push.rocks/smartdelay';
import * as smartpromise from '@push.rocks/smartpromise';
export {
smartdelay,
smartpromise
}
export { smartdelay, smartpromise };
// third party scope
import fastDeepEqual from 'fast-deep-equal';
export {
fastDeepEqual,
}
export { fastDeepEqual };

14
tsconfig.json Normal file
View File

@ -0,0 +1,14 @@
{
"compilerOptions": {
"experimentalDecorators": 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"
}