2025-04-28 19:10:27 +00:00
|
|
|
import { Assertion } from '../smartexpect.classes.assertion.js';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Namespace for function-specific matchers
|
|
|
|
*/
|
|
|
|
export class FunctionMatchers {
|
|
|
|
constructor(private assertion: Assertion<Function>) {}
|
|
|
|
|
|
|
|
toThrow(expectedError?: any) {
|
2025-04-28 19:58:32 +00:00
|
|
|
return this.assertion.customAssertion(
|
|
|
|
(value) => {
|
|
|
|
let threw = false;
|
|
|
|
try {
|
|
|
|
(value as Function)();
|
|
|
|
} catch (e: any) {
|
|
|
|
threw = true;
|
|
|
|
if (expectedError) {
|
|
|
|
if (typeof expectedError === 'function') {
|
|
|
|
return e instanceof expectedError;
|
|
|
|
}
|
|
|
|
return e === expectedError;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return threw;
|
|
|
|
},
|
|
|
|
`Expected function to throw${expectedError ? ` ${expectedError}` : ''}`
|
|
|
|
);
|
2025-04-28 19:10:27 +00:00
|
|
|
}
|
2025-04-28 20:42:58 +00:00
|
|
|
/**
|
|
|
|
* Assert thrown error message matches the given regex
|
|
|
|
*/
|
|
|
|
toThrowErrorMatching(regex: RegExp) {
|
|
|
|
return this.assertion.customAssertion(
|
|
|
|
(value) => {
|
|
|
|
try {
|
|
|
|
(value as Function)();
|
|
|
|
} catch (e: any) {
|
|
|
|
return regex.test(e && e.message);
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
},
|
|
|
|
`Expected function to throw error matching ${regex}`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
/**
|
|
|
|
* Assert thrown error message equals the given string
|
|
|
|
*/
|
|
|
|
toThrowErrorWithMessage(expectedMessage: string) {
|
|
|
|
return this.assertion.customAssertion(
|
|
|
|
(value) => {
|
|
|
|
try {
|
|
|
|
(value as Function)();
|
|
|
|
} catch (e: any) {
|
|
|
|
return e && e.message === expectedMessage;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
},
|
|
|
|
`Expected function to throw error with message "${expectedMessage}"`
|
|
|
|
);
|
|
|
|
}
|
2025-04-28 19:10:27 +00:00
|
|
|
}
|