Scoped cleanup
Rstest supports scoped cleanup for temporary test changes. When your runtime or toolchain supports explicit resource management, you can use using to automatically restore resources at the end of a block.
This is useful when a test temporarily changes shared state, such as spies, environment variables, globals, or fake timers.
Disposable using syntax
rs.stubEnv(), rs.stubGlobal(), and rs.useFakeTimers() return disposable resources that work with using.
Spy cleanup
Mocks and spies implement Symbol.dispose, so a spy created with rs.spyOn() is restored when the using block exits.
See Mock for more spy examples.
Environment variables
rs.stubEnv() returns a disposable resource. When it leaves a using scope, only that scoped env stub is restored.
Nested env stubs are restored in reverse order:
You can still call rs.unstubAllEnvs() to restore all env stubs in the current test.
Globals
rs.stubGlobal() also returns a disposable resource. This is convenient for temporarily replacing global APIs.
You can still call rs.unstubAllGlobals() to restore all global stubs in the current test.
Fake timers
rs.useFakeTimers() returns a disposable resource that restores real timers when the block exits.
Async resources
For asynchronous resources that implement Symbol.asyncDispose, use await using. Rstest's browser provider resources support async disposal internally so provider pages, contexts, and browsers can be closed by the same explicit resource management protocol.
Use using for synchronous cleanup and await using when cleanup needs to await asynchronous work.