You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/JestObjectAPI.md
+53Lines changed: 53 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -710,6 +710,59 @@ test('plays video', () => {
710
710
});
711
711
```
712
712
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
+
returnSymbol.for('nodejs.dispose');
759
+
},
760
+
});
761
+
}
762
+
```
763
+
764
+
:::
765
+
713
766
### `jest.spyOn(object, methodName, accessType?)`
714
767
715
768
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