Skip to content

fix(assert): hint that function properties compare by reference#7165

Open
LeSingh1 wants to merge 1 commit into
denoland:mainfrom
LeSingh1:assert-equals-function-hint
Open

fix(assert): hint that function properties compare by reference#7165
LeSingh1 wants to merge 1 commit into
denoland:mainfrom
LeSingh1:assert-equals-function-hint

Conversation

@LeSingh1

Copy link
Copy Markdown
Contributor

Fixes #6878.

When assertEquals throws on inputs that only differ in a function property, the diff prints both sides as the same [Function: name] string. The failure then looks like "both sides are identical, why did this throw?".

Repro from the issue:

import { assertEquals } from "jsr:@std/assert";
assertEquals(
  { x: 1, y: () => console.log(2) },
  { x: 1, y: () => console.log(2) },
);

Before:

error: AssertionError: Values are not equal.

    [Diff] Actual / Expected

    {
      x: 1,
      y: [Function: y],
    }

After:

error: AssertionError: Values are not equal.
  Note: function properties are compared by reference, so two distinct
  functions print the same as `[Function: name]` but are not equal.

    [Diff] Actual / Expected

    {
      x: 1,
      y: [Function: y],
    }

Implementation: a small containsFunction walker checks own properties, array entries, Map values, and Set elements (cycle-safe via a WeakSet) and the hint is appended only when at least one operand contains a function. No change to equality semantics or to the diff itself.

Tests cover: the issue's object case, arrays of functions, and a negative case confirming the hint does not appear for function-free inputs. Full assert/ suite (140 tests) passes.

assertEquals throws on inputs that only differ in a function property,
but the diff prints both sides as the same [Function: name] string,
which makes the failure look like "both sides identical, why did it
throw?".

Detect function values anywhere in either operand (own properties,
array entries, Map values, Set elements; cycle-safe) and prepend a
short note explaining that functions compare by reference. No change
to the diff itself or to equality semantics.

Fixes denoland#6878
@codecov

codecov Bot commented May 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.44444% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 94.57%. Comparing base (cdf74a8) to head (e0aa7b0).
⚠️ Report is 18 commits behind head on main.

Files with missing lines Patch % Lines
assert/equals.ts 94.44% 0 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7165      +/-   ##
==========================================
- Coverage   94.57%   94.57%   -0.01%     
==========================================
  Files         636      636              
  Lines       52142    52178      +36     
  Branches     9401     9417      +16     
==========================================
+ Hits        49315    49349      +34     
  Misses       2249     2249              
- Partials      578      580       +2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@bartlomieju bartlomieju left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice fix for a real papercut — the implementation is clean and the tests cover positive, nested, and negative cases. My main ask is to narrow the heuristic so the note doesn't attach to unrelated failures; details inline. Non-blocking notes on getter side effects and test style are also inline.

One broader point that doesn't map to a single line: the JSDoc (lines 18-22) already documents that Blob/Request-like async-only data also falls back to reference equality and hits the same "identical-looking diff" trap. If you adopt the actualString === expectedString gate suggested below, a slightly more general note ("…compared by reference, so two distinct values may print identically but not be equal") would also cover those cases for free — your call whether to keep it function-specific.

Comment thread assert/equals.ts
Comment on lines +92 to +98
if (
containsFunction(actual, new WeakSet()) ||
containsFunction(expected, new WeakSet())
) {
message +=
"\n Note: function properties are compared by reference, so two distinct functions print the same as `[Function: name]` but are not equal.";
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Main concern: this heuristic is too broad and produces noisy false positives.

The note fires whenever a function exists anywhere in either operand, even when the function is identical on both sides and unrelated to the inequality. Common case:

const handler = () => {};
assertEquals({ x: 1, onClick: handler }, { x: 2, onClick: handler });

Here onClick is the same reference on both sides — the real diff is x — yet the user gets a note about functions comparing by reference, which is irrelevant and misleading. std's own tests frequently compare objects holding identical method/handler references while other fields differ, so this would attach a spurious note to many existing failures.

Suggest gating on the genuinely-confusing condition: the formatted strings are identical but the values are unequal. That's exactly the issue's scenario, never fires when the diff is already meaningful, and skips the tree walk in the common case:

const actualString = format(actual);
const expectedString = format(expected);
if (
  actualString === expectedString &&
  (containsFunction(actual, new WeakSet()) ||
   containsFunction(expected, new WeakSet()))
) {
  message += "\n  Note: ...";
}

This requires moving the check below the format() calls on lines 100-101.

Comment thread assert/equals.ts
Comment on lines +33 to +41
for (const k of Reflect.ownKeys(value as object)) {
if (
containsFunction(
(value as Record<string | symbol, unknown>)[k],
seen,
)
) {
return true;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reflect.ownKeys + value[k] invokes getters, including throwing ones. format() already inspects values so this is mostly pre-existing, but it means getters get invoked an extra time on the failure path, and a throwing getter would surface as a confusing error inside the assertion failure rather than the original AssertionError. Worth a try/catch around the property access. (The actualString === expectedString gate suggested above also shrinks this exposure to the rare identical-string case.)

Comment thread assert/equals_test.ts
Comment on lines +226 to +230
const message = stripAnsiCode((error as AssertionError).message);
if (!message.includes("function properties are compared by reference")) {
throw new Error(
`expected message to include the function-reference hint, got:\n${message}`,
);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor style: this file already imports from @std/assertassertStringIncludes(message, "function properties are compared by reference") is more idiomatic than the hand-rolled if (!message.includes(...)) throw new Error(...) and gives better failure output. Same applies to the array case (~line 243) and the negative case (use assertNotMatch/a plain assertEquals(message.includes(...), false) or assert(!...) at ~line 256).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

@std/assert/equals - assertEquals() fails with function properties without displaying why

2 participants