Skip to content

Commit 0c8014f

Browse files
committed
Update docs
1 parent 61ce3ef commit 0c8014f

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

docs/JestObjectAPI.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -578,6 +578,51 @@ Returns the `jest` object for chaining.
578578

579579
Restores all mocks back to their original value. Equivalent to calling [`.mockRestore()`](MockFunctionAPI.md#mockfnmockrestore) on every mocked function. Beware that `jest.restoreAllMocks()` only works when the mock was created with `jest.spyOn`; other mocks will require you to manually restore them.
580580

581+
### `jest.mocked<T>(item: T, deep = false)`
582+
583+
The `mocked` test helper provides typings on your mocked modules and even their deep methods, based on the typing of its source. It makes use of the latest TypeScript feature, so you even have argument types completion in the IDE (as opposed to `jest.MockInstance`).
584+
585+
_Note: while it needs to be a function so that input type is changed, the helper itself does nothing else than returning the given input value._
586+
587+
Example:
588+
589+
```ts
590+
// foo.ts
591+
export const foo = {
592+
a: {
593+
b: {
594+
c: {
595+
hello: (name: string) => `Hello, ${name}`,
596+
},
597+
},
598+
},
599+
name: () => 'foo',
600+
}
601+
```
602+
603+
```ts
604+
// foo.spec.ts
605+
import { foo } from './foo'
606+
jest.mock('./foo')
607+
608+
// here the whole foo var is mocked deeply
609+
const mockedFoo = jest.mocked(foo, true)
610+
611+
test('deep', () => {
612+
// there will be no TS error here, and you'll have completion in modern IDEs
613+
mockedFoo.a.b.c.hello('me')
614+
// same here
615+
expect(mockedFoo.a.b.c.hello.mock.calls).toHaveLength(1)
616+
})
617+
618+
test('direct', () => {
619+
foo.name()
620+
// here only foo.name is mocked (or its methods if it's an object)
621+
expect(mocked(foo.name).mock.calls).toHaveLength(1)
622+
})
623+
```
624+
625+
581626
## Mock Timers
582627

583628
### `jest.useFakeTimers(implementation?: 'modern' | 'legacy')`

0 commit comments

Comments
 (0)