Skip to content

feat: restore spies automatically with using - #58

Merged
sheremet-va merged 3 commits into
tinylibs:mainfrom
privatenumber:feat/disposable-spies
Sep 4, 2026
Merged

sheremet-va merged 3 commits into
tinylibs:mainfrom
privatenumber:feat/disposable-spies

Conversation

@privatenumber

Copy link
Copy Markdown
Contributor

Problem

spyOn() replaces an object's property until the test calls .restore(). If a test returns early or throws first, the replacement can remain installed and affect later assertions.

ECMAScript explicit resource management defines [Symbol.dispose]() as the synchronous cleanup hook for using declarations. TypeScript's using documentation specifies that this cleanup also runs when a scope exits through an error or early return.

For example, using request = spyOn(service, 'request') had no cleanup behavior, so test authors needed a try/finally block to guarantee restoration.

Closes #57

Changes

spyOn() results now expose [Symbol.dispose]() as the existing .restore() operation. Tests can scope a replacement to a block and have the original property restored automatically:

{
  using request = spyOn(service, 'request').willCall(mockRequest)

  // `service.request` is mocked here.
}
// `service.request` is restored here.

The runtime hook is defined only when Symbol.dispose exists, so the package continues to load on its supported older Node.js versions. The new behavior covers normal scope exit and error unwinding.

@privatenumber
privatenumber marked this pull request as ready for review August 29, 2026 23:28
Comment thread src/internal.ts Outdated
@privatenumber

Copy link
Copy Markdown
Contributor Author

@sheremet-va Addressed!

@sheremet-va
sheremet-va merged commit cc450e5 into tinylibs:main Sep 4, 2026
1 check passed
@sheremet-va

Copy link
Copy Markdown
Member

LGMT!

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.

feat: support disposable spies with Symbol.dispose

2 participants