|
| 1 | +/** |
| 2 | + * Containment assertion for strings and arrays. |
| 3 | + */ |
| 4 | + |
| 5 | +import { Assertion } from "./Assertion.ts"; |
| 6 | +import { AssertionError } from "./AssertionError.ts"; |
| 7 | + |
| 8 | +/** |
| 9 | + * Deep equality check for containment comparison. |
| 10 | + */ |
| 11 | +const isDeepEqual = (a: any, b: any): boolean => { |
| 12 | + if (a === b) return true; |
| 13 | + if (a === null || b === null) return false; |
| 14 | + if (typeof a !== typeof b) return false; |
| 15 | + |
| 16 | + if (typeof a === "object" && typeof b === "object") { |
| 17 | + const aKeys = Object.keys(a); |
| 18 | + const bKeys = Object.keys(b); |
| 19 | + |
| 20 | + if (aKeys.length !== bKeys.length) return false; |
| 21 | + |
| 22 | + for (const key of aKeys) { |
| 23 | + if (!isDeepEqual(a[key], b[key])) { |
| 24 | + return false; |
| 25 | + } |
| 26 | + } |
| 27 | + return true; |
| 28 | + } |
| 29 | + |
| 30 | + return false; |
| 31 | +}; |
| 32 | + |
| 33 | +/** |
| 34 | + * Assert that a value contains the expected item. |
| 35 | + * |
| 36 | + * For strings: checks if the string contains the expected substring. |
| 37 | + * For arrays: checks if the array contains the expected item (using deep equality for objects). |
| 38 | + * |
| 39 | + * @example |
| 40 | + * await assertThat("hello world", contains("world")); // pass |
| 41 | + * await assertThat([1, 2, 3], contains(2)); // pass |
| 42 | + * await assertThat([{a: 1}, {b: 2}], contains({a: 1})); // pass (deep equality) |
| 43 | + */ |
| 44 | +export const contains = (expected: any): Assertion<string | any[]> => { |
| 45 | + return (actual: string | any[]): void => { |
| 46 | + if (typeof actual === "string") { |
| 47 | + if (typeof expected !== "string") { |
| 48 | + throw AssertionError({ |
| 49 | + message: "Expected string to contain a string, but got " + typeof expected, |
| 50 | + actual, |
| 51 | + expected, |
| 52 | + operator: "contains" |
| 53 | + }); |
| 54 | + } |
| 55 | + if (!actual.includes(expected)) { |
| 56 | + throw AssertionError({ |
| 57 | + message: "Expected string to contain " + JSON.stringify(expected) + " but got " + JSON.stringify(actual), |
| 58 | + actual, |
| 59 | + expected, |
| 60 | + operator: "contains" |
| 61 | + }); |
| 62 | + } |
| 63 | + } else if (Array.isArray(actual)) { |
| 64 | + const found = actual.some((item) => isDeepEqual(item, expected)); |
| 65 | + if (!found) { |
| 66 | + throw AssertionError({ |
| 67 | + message: "Expected array to contain " + JSON.stringify(expected) + " but got " + JSON.stringify(actual), |
| 68 | + actual, |
| 69 | + expected, |
| 70 | + operator: "contains" |
| 71 | + }); |
| 72 | + } |
| 73 | + } else { |
| 74 | + throw AssertionError({ |
| 75 | + message: "Expected string or array but got " + typeof actual, |
| 76 | + actual, |
| 77 | + expected, |
| 78 | + operator: "contains" |
| 79 | + }); |
| 80 | + } |
| 81 | + }; |
| 82 | +}; |
0 commit comments