Skip to content

Feat async extended matchers - #7213

Open
lowlighter wants to merge 3 commits into
denoland:mainfrom
lowlighter:feat-async-extended-matchers
Open

Feat async extended matchers#7213
lowlighter wants to merge 3 commits into
denoland:mainfrom
lowlighter:feat-async-extended-matchers

Conversation

@lowlighter

@lowlighter lowlighter commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

This allows extended matchers in expect to return either ExtendMatchResult or Promise<ExtendMatchResult>

This changes provides additional possibilities for custom matchers, like implementing a expect(value).toBeResolved() matcher.

Example:

const { promise, resolve } = Promise.withResolvers<void>();
await expect(promise).not.toBeResolved();
resolve();
await expect(promise).toBeResolved();

// NB: this is different from expect(promise).resolves.toBe()
// Here we test the actual promise state, not its resolved value

This is just an example, but it can be used for any custom matcher that requires async operations on the right side
(for example one could image matching agains dynamically fetched files, database query results, etc.)

Side note: While this PR doesn't address specifically the following issues, the example (in the diff of the test file) shows how to implement a matcher to test promise states

This is a reopen of #6806, i mistakenly closed it by deleting my fork

@github-actions github-actions Bot added the expect label Jul 5, 2026
@codecov

codecov Bot commented Jul 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.84%. Comparing base (3b390d0) to head (64c2974).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #7213   +/-   ##
=======================================
  Coverage   94.84%   94.84%           
=======================================
  Files         617      618    +1     
  Lines       51674    51690   +16     
  Branches     9350     9355    +5     
=======================================
+ Hits        49008    49024   +16     
  Misses       2121     2121           
  Partials      545      545           

☔ 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.

Thanks — async custom matchers are a real gap versus Jest, and the core approach (widen Matcher, branch on the returned value) is the right shape. The test that inspects actual promise state via Promise.race is a nice demonstration of why the feature is worth having.

Three things I'd want addressed before this lands, since @std/expect is stable (1.0.20) and this permanently commits the matcher contract. The instanceof Promise check is the one that's an outright bug; the missing-await footgun is the one users will actually get burned by.

Also: the PR title needs to be conventional-commit form for Validate PR title to pass — feat(expect): add support for async extended matchers or similar.

Comment thread expect/expect.ts
| ExtendMatchResult
| Promise<ExtendMatchResult>;

if (result instanceof Promise) {

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.

instanceof Promise is too narrow, and the failure is silent rather than loud.

A non-native thenable — a userland promise implementation, a Promise from another realm/worker, or anything with a .then — fails this check and falls into the sync branch. There, result.pass is undefined, so the assertion inverts: it always throws for a plain expectation and always passes under .not. A matcher that silently passes is the worst outcome for a test library.

This module already has isPromiseLike for exactly this; using it here also makes the behaviour consistent with how .resolves/.rejects decide what counts as a promise.

Comment thread expect/expect.ts
| Promise<ExtendMatchResult>;

if (result instanceof Promise) {
return result.then((result) => {

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.

Worth extracting the shared body rather than duplicating it. This block and the sync branch below are verbatim identical — same isNot/pass logic, same AssertionError, same emitAssertionTrigger(). Two copies of assertion-throwing logic will drift, and a fix applied to one won't obviously need applying to the other.

Something like a local check(result) called from both branches keeps them honest.

Separately, note that moving emitAssertionTrigger() into a .then() means it now fires a microtask later than in the sync path — so an un-awaited async matcher doesn't just pass silently, it also undercounts against expect.assertions(). Worth a test either way, since expect.assertions() is precisely the mechanism a user would reach for to catch a forgotten await.

Comment thread expect/_types.ts
context: MatcherContext,
...args: any[]
) => MatchResult | ExtendMatchResult;
) => MatchResult | ExtendMatchResult | Promise<ExtendMatchResult>;

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.

This is where the missing-await hazard originates, and I think it needs addressing before the feature ships.

await expect(p).toBeResolved() works, but expect(p).toBeResolved() without the await silently passes — the returned promise is dropped and any AssertionError inside it becomes an unhandled rejection at best. A test that asserts nothing but reports success is the failure mode a test library most needs to avoid.

The type system doesn't help here either: the call-site signature comes entirely from the user's own declare module augmentation, so there's nothing for a no-floating-promises lint to catch unless the user happens to declare it correctly. The test in this PR declares toBeResolved: () => Promise<ExtendMatchResult>, which isn't what the call actually resolves to — it resolves to void — so even the example gets this subtly wrong.

At minimum, expect.extend's JSDoc needs to state that a matcher may return a promise and that the resulting expectation must be awaited. Better would be documenting the correct augmentation shape (() => Promise<void>) so users get lint coverage for free.

Comment thread expect/_extend_test.ts
myexpect.anything;
});

Deno.test("expect.extend() api test case", async () => {

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.

This test name is byte-identical to the existing one at line 83, so the two are indistinguishable in test output — and deno test --filter will match both. Something like "expect.extend() supports async matchers" would describe what it actually covers.

While you're here, three cases worth adding: an async matcher under .resolves/.rejects (the isPromised path should flatten it, but nothing pins that), the expect.assertions() interaction noted above, and a matcher whose promise rejects rather than resolving to pass: false.

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.

3 participants