-
Notifications
You must be signed in to change notification settings - Fork 5.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(std/testing): Add support for object assertion against object subset #8001
Changes from 2 commits
43afcb9
2900260
5ba59ca
dcda844
b80372b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -429,6 +429,44 @@ export function assertNotMatch( | |
} | ||
} | ||
|
||
/** | ||
* Make an assertion that `actual` object is a subset of `expected` object, deeply. | ||
* If not, then throw. | ||
*/ | ||
export function assertObjectMatch( | ||
actual: { [key: string]: unknown }, | ||
expected: { [key: string]: unknown }, | ||
): void { | ||
type loose = { [key: string]: unknown }; | ||
const seen = new WeakMap(); | ||
return assertEquals( | ||
(function filter(a: loose, b: loose): loose { | ||
// Prevent infinite loop with circular references with same filter | ||
if ((seen.has(a)) && (seen.get(a) === b)) { | ||
return a; | ||
} | ||
seen.set(a, b); | ||
// Iterate through keys present in both actual and expected | ||
// and filter recursively on object references | ||
const filtered = {} as loose; | ||
for ( | ||
const [key, value] of Object.entries(a).filter(([key]) => key in b) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I replaced I got some trouble with using I wanted to add an erroneous case like you suggested, but seems that import { assertEquals } from "https://deno.land/std/testing/asserts.ts"
const foo = Symbol("foo")
Deno.test("symbol1", () => assertEquals({[foo]:"bar"}, {[foo]:"bar"}))
Deno.test("symbol2", () => assertEquals({[foo]:"bar"}, {[Symbol("foo")]:"bar"}))
|
||
) { | ||
if (typeof value === "object") { | ||
const subset = (b as loose)[key]; | ||
if ((typeof subset === "object") && (subset)) { | ||
filtered[key] = filter(value as loose, subset as loose); | ||
continue; | ||
} | ||
} | ||
filtered[key] = value; | ||
} | ||
return filtered; | ||
})(actual, expected), | ||
expected, | ||
); | ||
} | ||
|
||
/** | ||
* Forcefully throws a failed assertion | ||
*/ | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should symbols be allowed?