89 lines
2.3 KiB
TypeScript
Raw Normal View History

import { Assertion } from '../smartexpect.classes.assertion.js';
import * as plugins from '../plugins.js';
/**
* Namespace for object-specific matchers
*/
export class ObjectMatchers<T extends object> {
constructor(private assertion: Assertion<T>) {}
toEqual(expected: any) {
return this.assertion.customAssertion(
(v) => plugins.fastDeepEqual(v, expected),
`Expected objects to be deeply equal to ${JSON.stringify(expected)}`
);
}
toMatchObject(expected: object) {
return this.assertion.customAssertion(
(v) => {
for (const key of Object.keys(expected)) {
if (!plugins.fastDeepEqual((v as any)[key], (expected as any)[key])) {
return false;
}
}
return true;
},
`Expected object to match properties ${JSON.stringify(expected)}`
);
}
toBeInstanceOf(constructor: any) {
return this.assertion.customAssertion(
(v) => (v as any) instanceof constructor,
`Expected object to be instance of ${constructor.name || constructor}`
);
}
toHaveProperty(property: string, value?: any) {
return this.assertion.customAssertion(
(v) => {
const obj = v as any;
if (!(property in obj)) {
return false;
}
if (arguments.length === 2) {
return plugins.fastDeepEqual(obj[property], value);
}
return true;
},
`Expected object to have property ${property}${value !== undefined ? ` with value ${JSON.stringify(value)}` : ''}`
);
}
toHaveDeepProperty(path: string[]) {
return this.assertion.customAssertion(
(v) => {
let obj: any = v;
for (const key of path) {
if (obj == null || !(key in obj)) {
return false;
}
obj = obj[key];
}
return true;
},
`Expected object to have deep property path ${JSON.stringify(path)}`
);
}
toBeNull() {
return this.assertion.customAssertion(
(v) => v === null,
`Expected value to be null`
);
}
toBeUndefined() {
return this.assertion.customAssertion(
(v) => v === undefined,
`Expected value to be undefined`
);
}
toBeNullOrUndefined() {
return this.assertion.customAssertion(
(v) => v === null || v === undefined,
`Expected value to be null or undefined`
);
}
}