Skip to content

rewrite async test mocking example to use stub() with auto-restore#3119

Merged
bartlomieju merged 2 commits into
mainfrom
docs-improve/testing-async-stub-mock
May 14, 2026
Merged

rewrite async test mocking example to use stub() with auto-restore#3119
bartlomieju merged 2 commits into
mainfrom
docs-improve/testing-async-stub-mock

Conversation

@fibibot
Copy link
Copy Markdown
Contributor

@fibibot fibibot commented May 14, 2026

The Testing async functions section in examples/tutorials/testing.md
demonstrates how to mock fetch when testing async functions. The previous
example had two problems that bite anyone who copies it:

  1. globalThis.fetch = async (url: string) => … fails type-checking on
    stable Deno — the real fetch accepts URL | RequestInfo, not just
    string. Running deno test against the existing snippet on Deno
    2.7.14 produced TS2322: Type '(url: string) => Promise<Response>' is not assignable to type '…(input: URL | RequestInfo, init?: …)…'.
  2. The plain reassignment never restored the original fetch, so the
    mock leaked into every later test in the file. The page didn't mention
    this, so a reader following the pattern would silently break test
    isolation.

This PR rewrites that single section to use stub from
@std/testing/mock bound with
a using declaration. The stub matches fetch's real signature (the
file type-checks) and the disposer restores the original when each test
scope exits. A :::tip callout explains why the old shape was wrong so
readers learn the rule, not just the snippet. Filenames also moved from
dashes to underscores per runtime/contributing/style_guide.md.

Verified by running both tests plus a third "fetch is restored" probe
against denoland/deno:latest (2.7.14 — canary tag isn't published to
Docker Hub right now): Check async_test.ts passed and all 3 tests
passed in 5ms. The output block in the page is the real deno test
output from that run.

Closes bartlomieju/orchid-inbox#46

The previous example assigned to `globalThis.fetch` directly, which
fails type-checking on stable (signature mismatch) and leaks the mock
into every later test in the file. Switch to `stub` from
`@std/testing/mock` with a `using` declaration so the original `fetch`
is restored automatically when each test exits.
@fibibot
Copy link
Copy Markdown
Contributor Author

fibibot commented May 14, 2026

@bartlomieju ready for review when you have a moment.

@bartlomieju bartlomieju merged commit 06ee40a into main May 14, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants