Compare commits

..

10 Commits

6 changed files with 3454 additions and 421 deletions

View File

@ -1,5 +1,38 @@
# Changelog
## 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

View File

@ -1,6 +1,6 @@
{
"name": "@push.rocks/smartexpect",
"version": "1.1.0",
"version": "1.5.0",
"private": false,
"description": "A testing library to manage expectations in code, offering both synchronous and asynchronous assertion methods.",
"main": "dist_ts/index.js",
@ -18,12 +18,12 @@
"@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"
"@push.rocks/tapbundle": "^5.5.6",
"@types/node": "^22.13.9"
},
"dependencies": {
"@push.rocks/smartdelay": "^3.0.5",
"@push.rocks/smartpromise": "^4.0.4",
"@push.rocks/smartpromise": "^4.2.3",
"fast-deep-equal": "^3.1.3"
},
"browserslist": [
@ -57,5 +57,10 @@
"repository": {
"type": "git",
"url": "https://code.foss.global/push.rocks/smartexpect.git"
},
"pnpm": {
"onlyBuiltDependencies": [
"mongodb-memory-server"
]
}
}

3520
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartexpect',
version: '1.1.0',
version: '1.5.0',
description: 'A testing library to manage expectations in code, offering both synchronous and asynchronous assertion methods.'
}

View File

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

View File

@ -5,9 +5,13 @@ export type TExecutionType = 'sync' | 'async';
export class Assertion {
executionMode: TExecutionType;
baseReference: any;
propertyDrillDown: string[] = [];
propertyDrillDown: Array<string | number> = [];
private notSetting = false;
private timeoutSetting = 0;
private failMessage: string;
private successMessage: string;
constructor(baseReferenceArg: any, executionModeArg: TExecutionType) {
this.baseReference = baseReferenceArg;
this.executionMode = executionModeArg;
@ -16,6 +20,14 @@ export class Assertion {
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;
@ -31,6 +43,16 @@ export class Assertion {
return this;
}
public setFailMessage(failMessageArg: string) {
this.failMessage = failMessageArg;
return this;
}
public setSuccessMessage(successMessageArg: string) {
this.successMessage = successMessageArg;
return this;
}
private runCheck(checkFunction: () => any) {
const runDirectOrNegated = (checkFunction: () => any) => {
if (!this.notSetting) {
@ -43,7 +65,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!');
}
}
};
@ -60,7 +82,7 @@ export class Assertion {
}
});
}
this.baseReference.then((promiseResultArg) => {
this.baseReference.then((promiseResultArg: any) => {
this.baseReference = promiseResultArg;
done.resolve(runDirectOrNegated(checkFunction));
});
@ -71,26 +93,22 @@ 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(
this.failMessage ||
`Assertion failed: ${this.baseReference} with drill down ${
this.propertyDrillDown
} is not of type string, but typeof ${typeof this.baseReference}`
@ -103,6 +121,7 @@ export class Assertion {
return this.runCheck(() => {
if (typeof this.getObjectToTestReference() !== 'number') {
throw new Error(
this.failMessage ||
`Assertion failed: ${this.baseReference} with drill down ${
this.propertyDrillDown
} is not of type string, but typeof ${typeof this.baseReference}`
@ -115,6 +134,7 @@ export class Assertion {
return this.runCheck(() => {
if (typeof this.getObjectToTestReference() !== 'boolean') {
throw new Error(
this.failMessage ||
`Assertion failed: ${this.baseReference} with drill down ${
this.propertyDrillDown
} is not of type string, but typeof ${typeof this.baseReference}`
@ -128,6 +148,7 @@ export class Assertion {
const result = plugins.fastDeepEqual(this.getObjectToTestReference(), comparisonObject);
if (!result) {
throw new Error(
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} does not equal ${comparisonObject}`
);
}
@ -139,7 +160,10 @@ export class Assertion {
const result = comparisonObject.test(this.getObjectToTestReference());
if (!result) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not equal ${comparisonObject}`
this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not match regex ${comparisonObject}`
);
}
});
@ -152,6 +176,7 @@ export class Assertion {
this.getObjectToTestReference() === true;
if (!result) {
throw new Error(
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not true or not of type boolean`
);
}
@ -165,6 +190,7 @@ export class Assertion {
this.getObjectToTestReference() === false;
if (!result) {
throw new Error(
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not false or not of type boolean`
);
}
@ -176,24 +202,45 @@ export class Assertion {
const result = this.getObjectToTestReference() instanceof classArg;
if (!result) {
throw new Error(
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not an instance of ${classArg}`
);
}
});
}
public toBeTypeOf(expectedType: string) {
return this.runCheck(() => {
const actualType = typeof this.getObjectToTestReference();
if (actualType !== expectedType) {
throw new Error(
this.failMessage ||
`Assertion failed: ${this.baseReference} with drill down ${
this.propertyDrillDown
} is not of type ${expectedType}, but typeof ${actualType}`
);
}
});
}
public toHaveProperty(propertyArg: string, equalsArg?: any) {
return this.runCheck(() => {
const result = !!this.getObjectToTestReference()[propertyArg];
if (!result) {
const obj = this.getObjectToTestReference();
if (!obj || !(propertyArg in obj)) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not have property ${propertyArg}`
this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not have property ${propertyArg}`
);
}
if (equalsArg) {
if (result !== equalsArg) {
if (equalsArg !== undefined) {
if (obj[propertyArg] !== equalsArg) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does have property ${propertyArg}, but it does not equal ${equalsArg}`
this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does have property ${propertyArg}, but it does not equal ${equalsArg}`
);
}
}
@ -213,7 +260,10 @@ export class Assertion {
}
if (!obj || !(property in obj)) {
throw new Error(`Missing property at path "${currentPath}" in ${this.baseReference}`);
throw new Error(
this.failMessage ||
`Missing property at path "${currentPath}" in ${this.baseReference}`
);
}
obj = obj[property];
}
@ -225,6 +275,7 @@ export class Assertion {
const result = this.getObjectToTestReference() > numberArg;
if (!result) {
throw new Error(
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not greater than ${numberArg}`
);
}
@ -236,6 +287,7 @@ export class Assertion {
const result = this.getObjectToTestReference() < numberArg;
if (!result) {
throw new Error(
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not less than ${numberArg}`
);
}
@ -247,6 +299,7 @@ export class Assertion {
const result = this.getObjectToTestReference() === null;
if (!result) {
throw new Error(
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not null`
);
}
@ -258,6 +311,7 @@ export class Assertion {
const result = this.getObjectToTestReference() === undefined;
if (!result) {
throw new Error(
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not undefined`
);
}
@ -266,26 +320,27 @@ export class Assertion {
public toBeNullOrUndefined() {
return this.runCheck(() => {
const result =
this.getObjectToTestReference() === null || this.getObjectToTestReference() === undefined;
const testRef = this.getObjectToTestReference();
const result = testRef === null || testRef === undefined;
if (!result) {
throw new Error(
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not null or undefined`
);
}
});
}
// Array
// Array checks
public toContain(itemArg: any) {
return this.runCheck(() => {
const result =
this.getObjectToTestReference() instanceof Array &&
this.getObjectToTestReference().includes(itemArg);
const testRef = this.getObjectToTestReference();
const result = Array.isArray(testRef) && testRef.includes(itemArg);
if (!result) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not contain ${itemArg}`
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} does not contain ${itemArg}`
);
}
});
@ -295,7 +350,10 @@ export class Assertion {
return this.runCheck(() => {
const arrayRef = this.getObjectToTestReference();
if (!Array.isArray(arrayRef) || arrayRef.length !== 0) {
throw new Error(`Expected ${this.baseReference} to be an empty array, but it was not.`);
throw new Error(
this.failMessage ||
`Expected ${this.baseReference} to be an empty array, but it was not.`
);
}
});
}
@ -304,12 +362,17 @@ export class Assertion {
return this.runCheck(() => {
const arrayRef = this.getObjectToTestReference();
if (!Array.isArray(arrayRef)) {
throw new Error(`Expected ${this.baseReference} to be an array.`);
throw new Error(
this.failMessage ||
`Expected ${this.baseReference} with drill down ${
this.propertyDrillDown
} to be an array.`
);
}
for (const value of values) {
if (!arrayRef.includes(value)) {
throw new Error(
this.failMessage ||
`Expected ${this.baseReference} to include value "${value}", but it did not.`
);
}
@ -321,11 +384,16 @@ export class Assertion {
return this.runCheck(() => {
const arrayRef = this.getObjectToTestReference();
if (!Array.isArray(arrayRef)) {
throw new Error(`Expected ${this.baseReference} to be an array.`);
throw new Error(
this.failMessage ||
`Expected ${this.baseReference} with drill down ${
this.propertyDrillDown
} to be an array.`
);
}
if (arrayRef.includes(value)) {
throw new Error(
this.failMessage ||
`Expected ${this.baseReference} to exclude value "${value}", but it included it.`
);
}
@ -338,7 +406,10 @@ export class Assertion {
const result = typeof testObject === 'string' && testObject.startsWith(itemArg);
if (!result) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not contain ${itemArg}`
this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not start with ${itemArg}`
);
}
});
@ -350,19 +421,21 @@ export class Assertion {
const result = typeof testObject === 'string' && testObject.endsWith(itemArg);
if (!result) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not contain ${itemArg}`
this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not end with ${itemArg}`
);
}
});
}
// ... previous code ...
public toBeOneOf(values: any[]) {
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}`
);
}
@ -374,7 +447,10 @@ export class Assertion {
const obj = this.getObjectToTestReference();
if (typeof obj.length !== 'number' || obj.length !== length) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not have a length of ${length}`
this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not have a length of ${length}`
);
}
});
@ -385,7 +461,10 @@ export class Assertion {
const difference = Math.abs(this.getObjectToTestReference() - value);
if (difference > Math.pow(10, -precision) / 2) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not close to ${value} up to ${precision} decimal places`
this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} is not close to ${value} up to ${precision} decimal places`
);
}
});
@ -400,6 +479,7 @@ export class Assertion {
thrown = true;
if (expectedError && !(e instanceof expectedError)) {
throw new Error(
this.failMessage ||
`Expected function to throw ${expectedError.name}, but it threw ${e.name}`
);
}
@ -414,6 +494,7 @@ export class Assertion {
return this.runCheck(() => {
if (!this.getObjectToTestReference()) {
throw new Error(
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not truthy`
);
}
@ -424,6 +505,7 @@ export class Assertion {
return this.runCheck(() => {
if (this.getObjectToTestReference()) {
throw new Error(
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not falsy`
);
}
@ -432,9 +514,12 @@ export class Assertion {
public toBeGreaterThanOrEqual(numberArg: number) {
return this.runCheck(() => {
if (this.getObjectToTestReference() <= numberArg) {
if (this.getObjectToTestReference() < numberArg) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not greater than or equal to ${numberArg}`
this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} is not greater than or equal to ${numberArg}`
);
}
});
@ -442,9 +527,12 @@ export class Assertion {
public toBeLessThanOrEqual(numberArg: number) {
return this.runCheck(() => {
if (this.getObjectToTestReference() >= numberArg) {
if (this.getObjectToTestReference() > numberArg) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} is not less than or equal to ${numberArg}`
this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} is not less than or equal to ${numberArg}`
);
}
});
@ -452,10 +540,14 @@ export class Assertion {
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) {
// Implement a partial object match if needed.
const matchResult = plugins.fastDeepEqual(this.getObjectToTestReference(), objectArg);
if (!matchResult) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not match the object ${objectArg}`
this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not match the object ${JSON.stringify(objectArg)}`
);
}
});
@ -464,10 +556,18 @@ export class Assertion {
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 (!Array.isArray(arr)) {
throw new Error(
this.failMessage || `Expected ${this.baseReference} to be an array but it is not.`
);
}
const found = arr.some((item: any) => plugins.fastDeepEqual(item, value));
if (!found) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not contain the value ${value}`
this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not contain the value ${JSON.stringify(value)}`
);
}
});
@ -477,6 +577,7 @@ export class Assertion {
return this.runCheck(() => {
if (!Array.isArray(this.getObjectToTestReference())) {
throw new Error(
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not an array`
);
}
@ -485,9 +586,13 @@ export class Assertion {
public toInclude(substring: string) {
return this.runCheck(() => {
if (!this.getObjectToTestReference().includes(substring)) {
const testRef = this.getObjectToTestReference();
if (typeof testRef !== 'string' || !testRef.includes(substring)) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not include the substring ${substring}`
this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not include the substring ${substring}`
);
}
});
@ -498,7 +603,10 @@ export class Assertion {
const obj = this.getObjectToTestReference();
if (typeof obj.length !== 'number' || obj.length <= length) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not have a length greater than ${length}`
this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not have a length greater than ${length}`
);
}
});
@ -509,7 +617,10 @@ export class Assertion {
const obj = this.getObjectToTestReference();
if (typeof obj.length !== 'number' || obj.length >= length) {
throw new Error(
`${this.baseReference} with drill down ${this.propertyDrillDown} does not have a length less than ${length}`
this.failMessage ||
`${this.baseReference} with drill down ${
this.propertyDrillDown
} does not have a length less than ${length}`
);
}
});
@ -517,8 +628,10 @@ export class Assertion {
public toBeDate() {
return this.runCheck(() => {
if (!(this.getObjectToTestReference() instanceof Date)) {
const testRef = this.getObjectToTestReference();
if (!(testRef instanceof Date)) {
throw new Error(
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not a date`
);
}
@ -527,8 +640,10 @@ export class Assertion {
public toBeBeforeDate(date: Date) {
return this.runCheck(() => {
if (!(this.getObjectToTestReference() < date)) {
const testRef = this.getObjectToTestReference();
if (!(testRef instanceof Date) || testRef >= date) {
throw new Error(
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not before ${date}`
);
}
@ -537,24 +652,47 @@ export class Assertion {
public toBeAfterDate(date: Date) {
return this.runCheck(() => {
if (!(this.getObjectToTestReference() > date)) {
const testRef = this.getObjectToTestReference();
if (!(testRef instanceof Date) || testRef <= date) {
throw new Error(
this.failMessage ||
`${this.baseReference} with drill down ${this.propertyDrillDown} is not after ${date}`
);
}
});
}
public customAssertion(assertionFunction: (value: any) => boolean, errorMessage: string) {
public customAssertion(
assertionFunction: (value: any) => boolean,
errorMessage: string
) {
return this.runCheck(() => {
if (!assertionFunction(this.getObjectToTestReference())) {
throw new Error(errorMessage);
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(`this is the object to test:`);
console.log(JSON.stringify(this.getObjectToTestReference(), null, 2));
return this;
}
}