Skip to content

Commit fe13eee

Browse files
committed
add some docs
1 parent 82c82b1 commit fe13eee

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

docs/JestObjectAPI.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -710,6 +710,59 @@ test('plays video', () => {
710710
});
711711
```
712712

713+
#### spied methods and the `using` keyword
714+
715+
If your codebase is set up to transpile the ["explicit resource management"](https://github.com/tc39/proposal-explicit-resource-management) (e.g. if you are using TypeScript >= 5.2 or the `'@babel/plugin-proposal-explicit-resource-management'` plugin), you can use `spyOn` in combination with the `using` keyword:
716+
717+
```js
718+
test('logs a warning', () => {
719+
using spy = jest.spyOn(console.warn);
720+
doSomeThingWarnWorthy();
721+
expect(spy).toHaveBeenCalled();
722+
})
723+
```
724+
That code is semantically equal to
725+
```js
726+
test('logs a warning', () => {
727+
try {
728+
using spy = jest.spyOn(console.warn);
729+
doSomeThingWarnWorthy();
730+
expect(spy).toHaveBeenCalled();
731+
} finally {
732+
spy.mockRestore()
733+
}
734+
})
735+
```
736+
That way, your spy will automatically be restored to the original value once the current code block is left.
737+
738+
You can even go a step further and use a code block to restrict your mock to only a part of your test without hurting readability.
739+
```js
740+
test('testing something', () => {
741+
{
742+
using spy = jest.spyOn(console.warn);
743+
setupStepThatWillLogAWarning()
744+
}
745+
// here, console.warn is already restored to the original value
746+
// your test can now continue normally
747+
})
748+
```
749+
750+
:::note
751+
752+
If you get a warning that `Symbol.dispose` does not exist, you might need to polyfill that, e.g. with this code:
753+
754+
```js
755+
if (!Symbol.dispose) {
756+
Object.defineProperty(Symbol, 'dispose', {
757+
get() {
758+
return Symbol.for('nodejs.dispose');
759+
},
760+
});
761+
}
762+
```
763+
764+
:::
765+
713766
### `jest.spyOn(object, methodName, accessType?)`
714767

715768
Since Jest 22.1.0+, the `jest.spyOn` method takes an optional third argument of `accessType` that can be either `'get'` or `'set'`, which proves to be useful when you want to spy on a getter or a setter, respectively.

0 commit comments

Comments
 (0)