Skip to content

Commit

Permalink
add some docs
Browse files Browse the repository at this point in the history
  • Loading branch information
phryneas committed Feb 10, 2024
1 parent 82c82b1 commit fe13eee
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions docs/JestObjectAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,59 @@ test('plays video', () => {
});
```

#### spied methods and the `using` keyword

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:

```js
test('logs a warning', () => {
using spy = jest.spyOn(console.warn);
doSomeThingWarnWorthy();
expect(spy).toHaveBeenCalled();
})
```
That code is semantically equal to
```js
test('logs a warning', () => {
try {
using spy = jest.spyOn(console.warn);
doSomeThingWarnWorthy();
expect(spy).toHaveBeenCalled();
} finally {
spy.mockRestore()
}
})
```
That way, your spy will automatically be restored to the original value once the current code block is left.

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.
```js
test('testing something', () => {
{
using spy = jest.spyOn(console.warn);
setupStepThatWillLogAWarning()
}
// here, console.warn is already restored to the original value
// your test can now continue normally
})
```

:::note

If you get a warning that `Symbol.dispose` does not exist, you might need to polyfill that, e.g. with this code:

```js
if (!Symbol.dispose) {
Object.defineProperty(Symbol, 'dispose', {
get() {
return Symbol.for('nodejs.dispose');
},
});
}
```

:::

### `jest.spyOn(object, methodName, accessType?)`

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.
Expand Down

0 comments on commit fe13eee

Please sign in to comment.