@vitest-agent/mcp 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/README.md +1 -2
  2. package/index.d.ts +2 -2
  3. package/index.js +1 -1
  4. package/package.json +1 -1
  5. package/server.js +2 -4
  6. package/patterns/_meta.json +0 -67
  7. package/patterns/authoring-a-custom-vitest-agent-reporter.md +0 -82
  8. package/patterns/known-issues-and-caveats.md +0 -52
  9. package/patterns/operating-vitest-agent-as-an-agent.md +0 -62
  10. package/patterns/running-tests-via-mcp.md +0 -103
  11. package/patterns/silencing-leaking-output-in-tests.md +0 -91
  12. package/patterns/testing-effect-schema-definitions.md +0 -71
  13. package/patterns/testing-effect-services-with-mock-layers.md +0 -63
  14. package/resources/index.js +0 -166
  15. package/resources/indexes.js +0 -77
  16. package/resources/manifest-schema.js +0 -46
  17. package/resources/paths.js +0 -20
  18. package/resources/patterns.js +0 -22
  19. package/resources/upstream-docs.js +0 -22
  20. package/vendor/vitest-docs/ATTRIBUTION.md +0 -5
  21. package/vendor/vitest-docs/api/advanced/artifacts.md +0 -189
  22. package/vendor/vitest-docs/api/advanced/metadata.md +0 -68
  23. package/vendor/vitest-docs/api/advanced/plugin.md +0 -168
  24. package/vendor/vitest-docs/api/advanced/reporters.md +0 -342
  25. package/vendor/vitest-docs/api/advanced/runner.md +0 -334
  26. package/vendor/vitest-docs/api/advanced/test-case.md +0 -302
  27. package/vendor/vitest-docs/api/advanced/test-collection.md +0 -89
  28. package/vendor/vitest-docs/api/advanced/test-module.md +0 -140
  29. package/vendor/vitest-docs/api/advanced/test-project.md +0 -321
  30. package/vendor/vitest-docs/api/advanced/test-specification.md +0 -96
  31. package/vendor/vitest-docs/api/advanced/test-suite.md +0 -230
  32. package/vendor/vitest-docs/api/advanced/vitest.md +0 -684
  33. package/vendor/vitest-docs/api/assert-type.md +0 -22
  34. package/vendor/vitest-docs/api/assert.md +0 -1960
  35. package/vendor/vitest-docs/api/browser/assertions.md +0 -1277
  36. package/vendor/vitest-docs/api/browser/commands.md +0 -154
  37. package/vendor/vitest-docs/api/browser/context.md +0 -338
  38. package/vendor/vitest-docs/api/browser/interactivity.md +0 -681
  39. package/vendor/vitest-docs/api/browser/locators.md +0 -1171
  40. package/vendor/vitest-docs/api/browser/react.md +0 -346
  41. package/vendor/vitest-docs/api/browser/svelte.md +0 -292
  42. package/vendor/vitest-docs/api/browser/vue.md +0 -222
  43. package/vendor/vitest-docs/api/describe.md +0 -374
  44. package/vendor/vitest-docs/api/expect-typeof.md +0 -571
  45. package/vendor/vitest-docs/api/expect.md +0 -2304
  46. package/vendor/vitest-docs/api/hooks.md +0 -463
  47. package/vendor/vitest-docs/api/mock.md +0 -701
  48. package/vendor/vitest-docs/api/test.md +0 -926
  49. package/vendor/vitest-docs/api/vi.md +0 -1372
  50. package/vendor/vitest-docs/config/alias.md +0 -13
  51. package/vendor/vitest-docs/config/allowonly.md +0 -32
  52. package/vendor/vitest-docs/config/api.md +0 -27
  53. package/vendor/vitest-docs/config/attachmentsdir.md +0 -6
  54. package/vendor/vitest-docs/config/bail.md +0 -9
  55. package/vendor/vitest-docs/config/benchmark.md +0 -65
  56. package/vendor/vitest-docs/config/browser/api.md +0 -23
  57. package/vendor/vitest-docs/config/browser/commands.md +0 -6
  58. package/vendor/vitest-docs/config/browser/connecttimeout.md +0 -10
  59. package/vendor/vitest-docs/config/browser/detailspanelposition.md +0 -38
  60. package/vendor/vitest-docs/config/browser/enabled.md +0 -40
  61. package/vendor/vitest-docs/config/browser/expect.md +0 -250
  62. package/vendor/vitest-docs/config/browser/headless.md +0 -7
  63. package/vendor/vitest-docs/config/browser/instances.md +0 -47
  64. package/vendor/vitest-docs/config/browser/isolate.md +0 -11
  65. package/vendor/vitest-docs/config/browser/locators.md +0 -24
  66. package/vendor/vitest-docs/config/browser/orchestratorscripts.md +0 -39
  67. package/vendor/vitest-docs/config/browser/playwright.md +0 -214
  68. package/vendor/vitest-docs/config/browser/preview.md +0 -32
  69. package/vendor/vitest-docs/config/browser/provider.md +0 -79
  70. package/vendor/vitest-docs/config/browser/screenshotdirectory.md +0 -6
  71. package/vendor/vitest-docs/config/browser/screenshotfailures.md +0 -6
  72. package/vendor/vitest-docs/config/browser/testerhtmlpath.md +0 -5
  73. package/vendor/vitest-docs/config/browser/trace.md +0 -43
  74. package/vendor/vitest-docs/config/browser/trackunhandlederrors.md +0 -10
  75. package/vendor/vitest-docs/config/browser/ui.md +0 -7
  76. package/vendor/vitest-docs/config/browser/viewport.md +0 -6
  77. package/vendor/vitest-docs/config/browser/webdriverio.md +0 -64
  78. package/vendor/vitest-docs/config/cache.md +0 -26
  79. package/vendor/vitest-docs/config/chaiconfig.md +0 -29
  80. package/vendor/vitest-docs/config/clearmocks.md +0 -22
  81. package/vendor/vitest-docs/config/coverage.md +0 -455
  82. package/vendor/vitest-docs/config/css.md +0 -47
  83. package/vendor/vitest-docs/config/dangerouslyignoreunhandlederrors.md +0 -23
  84. package/vendor/vitest-docs/config/deps.md +0 -127
  85. package/vendor/vitest-docs/config/detectasyncleaks.md +0 -39
  86. package/vendor/vitest-docs/config/diff.md +0 -96
  87. package/vendor/vitest-docs/config/dir.md +0 -7
  88. package/vendor/vitest-docs/config/disableconsoleintercept.md +0 -15
  89. package/vendor/vitest-docs/config/env.md +0 -5
  90. package/vendor/vitest-docs/config/environment.md +0 -96
  91. package/vendor/vitest-docs/config/environmentoptions.md +0 -30
  92. package/vendor/vitest-docs/config/exclude.md +0 -49
  93. package/vendor/vitest-docs/config/execargv.md +0 -10
  94. package/vendor/vitest-docs/config/expandsnapshotdiff.md +0 -7
  95. package/vendor/vitest-docs/config/expect.md +0 -38
  96. package/vendor/vitest-docs/config/experimental.md +0 -510
  97. package/vendor/vitest-docs/config/faketimers.md +0 -51
  98. package/vendor/vitest-docs/config/fileparallelism.md +0 -11
  99. package/vendor/vitest-docs/config/forcereruntriggers.md +0 -19
  100. package/vendor/vitest-docs/config/globals.md +0 -42
  101. package/vendor/vitest-docs/config/globalsetup.md +0 -72
  102. package/vendor/vitest-docs/config/hideskippedtests.md +0 -7
  103. package/vendor/vitest-docs/config/hooktimeout.md +0 -7
  104. package/vendor/vitest-docs/config/include-source.md +0 -115
  105. package/vendor/vitest-docs/config/include.md +0 -71
  106. package/vendor/vitest-docs/config/includetasklocation.md +0 -17
  107. package/vendor/vitest-docs/config/index.md +0 -85
  108. package/vendor/vitest-docs/config/isolate.md +0 -13
  109. package/vendor/vitest-docs/config/logheapusage.md +0 -7
  110. package/vendor/vitest-docs/config/maxconcurrency.md +0 -9
  111. package/vendor/vitest-docs/config/maxworkers.md +0 -49
  112. package/vendor/vitest-docs/config/mockreset.md +0 -22
  113. package/vendor/vitest-docs/config/mode.md +0 -7
  114. package/vendor/vitest-docs/config/name.md +0 -111
  115. package/vendor/vitest-docs/config/onconsolelog.md +0 -25
  116. package/vendor/vitest-docs/config/onstacktrace.md +0 -32
  117. package/vendor/vitest-docs/config/onunhandlederror.md +0 -35
  118. package/vendor/vitest-docs/config/open.md +0 -7
  119. package/vendor/vitest-docs/config/outputfile.md +0 -7
  120. package/vendor/vitest-docs/config/passwithnotests.md +0 -7
  121. package/vendor/vitest-docs/config/pool.md +0 -45
  122. package/vendor/vitest-docs/config/printconsoletrace.md +0 -6
  123. package/vendor/vitest-docs/config/projects.md +0 -6
  124. package/vendor/vitest-docs/config/provide.md +0 -45
  125. package/vendor/vitest-docs/config/reporters.md +0 -69
  126. package/vendor/vitest-docs/config/resolvesnapshotpath.md +0 -36
  127. package/vendor/vitest-docs/config/restoremocks.md +0 -22
  128. package/vendor/vitest-docs/config/retry.md +0 -140
  129. package/vendor/vitest-docs/config/root.md +0 -6
  130. package/vendor/vitest-docs/config/runner.md +0 -6
  131. package/vendor/vitest-docs/config/sequence.md +0 -158
  132. package/vendor/vitest-docs/config/server.md +0 -68
  133. package/vendor/vitest-docs/config/setupfiles.md +0 -40
  134. package/vendor/vitest-docs/config/silent.md +0 -9
  135. package/vendor/vitest-docs/config/slowtestthreshold.md +0 -7
  136. package/vendor/vitest-docs/config/snapshotenvironment.md +0 -27
  137. package/vendor/vitest-docs/config/snapshotformat.md +0 -28
  138. package/vendor/vitest-docs/config/snapshotserializers.md +0 -6
  139. package/vendor/vitest-docs/config/stricttags.md +0 -30
  140. package/vendor/vitest-docs/config/tags.md +0 -141
  141. package/vendor/vitest-docs/config/teardowntimeout.md +0 -7
  142. package/vendor/vitest-docs/config/testnamepattern.md +0 -21
  143. package/vendor/vitest-docs/config/testtimeout.md +0 -7
  144. package/vendor/vitest-docs/config/typecheck.md +0 -77
  145. package/vendor/vitest-docs/config/ui.md +0 -15
  146. package/vendor/vitest-docs/config/unstubenvs.md +0 -20
  147. package/vendor/vitest-docs/config/unstubglobals.md +0 -20
  148. package/vendor/vitest-docs/config/update.md +0 -16
  149. package/vendor/vitest-docs/config/vmmemorylimit.md +0 -30
  150. package/vendor/vitest-docs/config/watch.md +0 -11
  151. package/vendor/vitest-docs/config/watchtriggerpatterns.md +0 -29
  152. package/vendor/vitest-docs/guide/advanced/index.md +0 -147
  153. package/vendor/vitest-docs/guide/advanced/pool.md +0 -148
  154. package/vendor/vitest-docs/guide/advanced/reporters.md +0 -93
  155. package/vendor/vitest-docs/guide/advanced/tests.md +0 -125
  156. package/vendor/vitest-docs/guide/browser/aria-snapshots.md +0 -470
  157. package/vendor/vitest-docs/guide/browser/component-testing.md +0 -571
  158. package/vendor/vitest-docs/guide/browser/index.md +0 -630
  159. package/vendor/vitest-docs/guide/browser/multiple-setups.md +0 -121
  160. package/vendor/vitest-docs/guide/browser/trace-view.md +0 -126
  161. package/vendor/vitest-docs/guide/browser/visual-regression-testing.md +0 -734
  162. package/vendor/vitest-docs/guide/cli-generated.md +0 -972
  163. package/vendor/vitest-docs/guide/cli.md +0 -234
  164. package/vendor/vitest-docs/guide/common-errors.md +0 -163
  165. package/vendor/vitest-docs/guide/coverage.md +0 -515
  166. package/vendor/vitest-docs/guide/debugging.md +0 -127
  167. package/vendor/vitest-docs/guide/environment.md +0 -101
  168. package/vendor/vitest-docs/guide/extending-matchers.md +0 -160
  169. package/vendor/vitest-docs/guide/features.md +0 -310
  170. package/vendor/vitest-docs/guide/filtering.md +0 -175
  171. package/vendor/vitest-docs/guide/ide.md +0 -43
  172. package/vendor/vitest-docs/guide/improving-performance.md +0 -245
  173. package/vendor/vitest-docs/guide/in-source.md +0 -159
  174. package/vendor/vitest-docs/guide/index.md +0 -128
  175. package/vendor/vitest-docs/guide/learn/async.md +0 -147
  176. package/vendor/vitest-docs/guide/learn/debugging-tests.md +0 -210
  177. package/vendor/vitest-docs/guide/learn/matchers.md +0 -277
  178. package/vendor/vitest-docs/guide/learn/mock-functions.md +0 -277
  179. package/vendor/vitest-docs/guide/learn/setup-teardown.md +0 -240
  180. package/vendor/vitest-docs/guide/learn/snapshots.md +0 -166
  181. package/vendor/vitest-docs/guide/learn/testing-in-practice.md +0 -430
  182. package/vendor/vitest-docs/guide/learn/writing-tests-with-ai.md +0 -127
  183. package/vendor/vitest-docs/guide/learn/writing-tests.md +0 -231
  184. package/vendor/vitest-docs/guide/lifecycle.md +0 -379
  185. package/vendor/vitest-docs/guide/migration.md +0 -863
  186. package/vendor/vitest-docs/guide/mocking/classes.md +0 -158
  187. package/vendor/vitest-docs/guide/mocking/dates.md +0 -52
  188. package/vendor/vitest-docs/guide/mocking/file-system.md +0 -74
  189. package/vendor/vitest-docs/guide/mocking/functions.md +0 -61
  190. package/vendor/vitest-docs/guide/mocking/globals.md +0 -20
  191. package/vendor/vitest-docs/guide/mocking/modules.md +0 -414
  192. package/vendor/vitest-docs/guide/mocking/requests.md +0 -114
  193. package/vendor/vitest-docs/guide/mocking/timers.md +0 -48
  194. package/vendor/vitest-docs/guide/mocking.md +0 -239
  195. package/vendor/vitest-docs/guide/open-telemetry.md +0 -156
  196. package/vendor/vitest-docs/guide/parallelism.md +0 -82
  197. package/vendor/vitest-docs/guide/profiling-test-performance.md +0 -243
  198. package/vendor/vitest-docs/guide/projects.md +0 -291
  199. package/vendor/vitest-docs/guide/recipes.md +0 -59
  200. package/vendor/vitest-docs/guide/reporters.md +0 -723
  201. package/vendor/vitest-docs/guide/snapshot.md +0 -620
  202. package/vendor/vitest-docs/guide/test-annotations.md +0 -103
  203. package/vendor/vitest-docs/guide/test-context.md +0 -902
  204. package/vendor/vitest-docs/guide/test-tags.md +0 -314
  205. package/vendor/vitest-docs/guide/testing-types.md +0 -149
  206. package/vendor/vitest-docs/guide/ui.md +0 -160
  207. package/vendor/vitest-docs/guide/using-plugins.md +0 -5
  208. package/vendor/vitest-docs/manifest.json +0 -1691
@@ -1,1372 +0,0 @@
1
- # Vi
2
-
3
- Vitest provides utility functions to help you out through its `vi` helper. You can access it globally (when [globals configuration](/config/globals) is enabled), or import it from `vitest` directly:
4
-
5
- ```js
6
- import { vi } from 'vitest'
7
- ```
8
-
9
- ## Mock Modules
10
-
11
- This section describes the API that you can use when [mocking a module](/guide/mocking/modules). Beware that Vitest doesn't support mocking modules imported using `require()`.
12
-
13
- ### vi.mock
14
-
15
- ```ts
16
- interface MockOptions {
17
- spy?: boolean
18
- }
19
-
20
- interface MockFactory<T> {
21
- (importOriginal: () => T): unknown
22
- }
23
-
24
- function mock(
25
- path: string,
26
- factory?: MockOptions | MockFactory<unknown>
27
- ): void
28
- function mock<T>(
29
- module: Promise<T>,
30
- factory?: MockOptions | MockFactory<T>
31
- ): void
32
- ```
33
-
34
- Substitutes all imported modules from provided `path` with another module. You can use configured Vite aliases inside a path. The call to `vi.mock` is hoisted, so it doesn't matter where you call it. It will always be executed before all imports. If you need to reference some variables outside of its scope, you can define them inside [`vi.hoisted`](#vi-hoisted) and reference them inside `vi.mock`.
35
-
36
- It is recommended to use `vi.mock` or `vi.hoisted` only inside test files. If Vite's [module runner](/config/experimental#experimental-vitemodulerunner) is disabled, they will not be hoisted. This is a performance optimisation to avoid ready unnecessary files.
37
-
38
- ::: warning
39
- `vi.mock` works only for modules that were imported with the `import` keyword. It doesn't work with `require`.
40
-
41
- In order to hoist `vi.mock`, Vitest statically analyzes your files. It indicates that `vi` that was not directly imported from the `vitest` package (for example, from some utility file) cannot be used. Use `vi.mock` with `vi` imported from `vitest`, or enable [`globals`](/config/globals) config option.
42
-
43
- Vitest will not mock modules that were imported inside a [setup file](/config/setupfiles) because they are cached by the time a test file is running. You can call [`vi.resetModules()`](#vi-resetmodules) inside [`vi.hoisted`](#vi-hoisted) to clear all module caches before running a test file.
44
- :::
45
-
46
- If the `factory` function is defined, all imports will return its result. Vitest calls factory only once and caches results for all subsequent imports until [`vi.unmock`](#vi-unmock) or [`vi.doUnmock`](#vi-dounmock) is called.
47
-
48
- Unlike in `jest`, the factory can be asynchronous. You can use [`vi.importActual`](#vi-importactual) or a helper with the factory passed in as the first argument, and get the original module inside.
49
-
50
- You can also provide an object with a `spy` property instead of a factory function. If `spy` is `true`, then Vitest will automock the module as usual, but it won't override the implementation of exports. This is useful if you just want to assert that the exported method was called correctly by another method.
51
-
52
- ```ts
53
- import { calculator } from './src/calculator.ts'
54
-
55
- vi.mock('./src/calculator.ts', { spy: true })
56
-
57
- // calls the original implementation,
58
- // but allows asserting the behaviour later
59
- const result = calculator(1, 2)
60
-
61
- expect(result).toBe(3)
62
- expect(calculator).toHaveBeenCalledWith(1, 2)
63
- expect(calculator).toHaveReturnedWith(3)
64
- ```
65
-
66
- Vitest also supports a module promise instead of a string in the `vi.mock` and `vi.doMock` methods for better IDE support. When the file is moved, the path will be updated, and `importOriginal` inherits the type automatically. Using this signature will also enforce factory return type to be compatible with the original module (keeping exports optional).
67
-
68
- ```ts twoslash
69
- // @filename: ./path/to/module.js
70
- export declare function total(...numbers: number[]): number
71
- // @filename: test.js
72
- import { vi } from 'vitest'
73
- // ---cut---
74
- vi.mock(import('./path/to/module.js'), async (importOriginal) => {
75
- const mod = await importOriginal() // type is inferred
76
- // ^?
77
- return {
78
- ...mod,
79
- // replace some exports
80
- total: vi.fn(),
81
- }
82
- })
83
- ```
84
-
85
- Under the hood, Vitest still operates on a string and not a module object.
86
-
87
- If you are using TypeScript with `paths` aliases configured in `tsconfig.json` however, the compiler won't be able to correctly resolve import types.
88
- In order to make it work, make sure to replace all aliased imports, with their corresponding relative paths.
89
- Eg. use `import('./path/to/module.js')` instead of `import('@/module')`.
90
-
91
- ::: warning
92
- `vi.mock` is hoisted (in other words, _moved_) to **top of the file**. It means that whenever you write it (be it inside `beforeEach` or `test`), it will actually be called before that.
93
-
94
- This also means that you cannot use any variables inside the factory that are defined outside the factory.
95
-
96
- If you need to use variables inside the factory, try [`vi.doMock`](#vi-domock). It works the same way but isn't hoisted. Beware that it only mocks subsequent imports.
97
-
98
- You can also reference variables defined by `vi.hoisted` method if it was declared before `vi.mock`:
99
-
100
- ```ts
101
- import { namedExport } from './path/to/module.js'
102
-
103
- const mocks = vi.hoisted(() => {
104
- return {
105
- namedExport: vi.fn(),
106
- }
107
- })
108
-
109
- vi.mock('./path/to/module.js', () => {
110
- return {
111
- namedExport: mocks.namedExport,
112
- }
113
- })
114
-
115
- vi.mocked(namedExport).mockReturnValue(100)
116
-
117
- expect(namedExport()).toBe(100)
118
- expect(namedExport).toBe(mocks.namedExport)
119
- ```
120
- :::
121
-
122
- ::: warning
123
- If you are mocking a module with default export, you will need to provide a `default` key within the returned factory function object. This is an ES module-specific caveat; therefore, `jest` documentation may differ as `jest` uses CommonJS modules. For example,
124
-
125
- ```ts
126
- vi.mock('./path/to/module.js', () => {
127
- return {
128
- default: { myDefaultKey: vi.fn() },
129
- namedExport: vi.fn(),
130
- // etc...
131
- }
132
- })
133
- ```
134
- :::
135
-
136
- If there is a `__mocks__` folder alongside a file that you are mocking, and the factory is not provided, Vitest will try to find a file with the same name in the `__mocks__` subfolder and use it as an actual module. If you are mocking a dependency, Vitest will try to find a `__mocks__` folder in the [root](/config/root) of the project (default is `process.cwd()`). You can tell Vitest where the dependencies are located through the [`deps.moduleDirectories`](/config/deps#deps-moduledirectories) config option.
137
-
138
- For example, you have this file structure:
139
-
140
- ```
141
- - __mocks__
142
- - axios.js
143
- - src
144
- __mocks__
145
- - increment.js
146
- - increment.js
147
- - tests
148
- - increment.test.js
149
- ```
150
-
151
- If you call `vi.mock` in a test file without a factory or options provided, it will find a file in the `__mocks__` folder to use as a module:
152
-
153
- ```ts [increment.test.js]
154
- import { vi } from 'vitest'
155
-
156
- // axios is a default export from `__mocks__/axios.js`
157
- import axios from 'axios'
158
-
159
- // increment is a named export from `src/__mocks__/increment.js`
160
- import { increment } from '../increment.js'
161
-
162
- vi.mock('axios')
163
- vi.mock('../increment.js')
164
-
165
- axios.get(`/apples/${increment(1)}`)
166
- ```
167
-
168
- ::: warning
169
- Beware that if you don't call `vi.mock`, modules **are not** mocked automatically. To replicate Jest's automocking behaviour, you can call `vi.mock` for each required module inside [`setupFiles`](/config/setupfiles).
170
- :::
171
-
172
- If there is no `__mocks__` folder or a factory provided, Vitest will import the original module and auto-mock all its exports. For the rules applied, see [algorithm](/guide/mocking/modules#automocking-algorithm).
173
-
174
- ### vi.doMock
175
-
176
- ```ts
177
- function doMock(
178
- path: string,
179
- factory?: MockOptions | MockFactory<unknown>
180
- ): Disposable
181
- function doMock<T>(
182
- module: Promise<T>,
183
- factory?: MockOptions | MockFactory<T>
184
- ): Disposable
185
- ```
186
-
187
- The same as [`vi.mock`](#vi-mock), but it's not hoisted to the top of the file, so you can reference variables in the global file scope. The next [dynamic import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) of the module will be mocked.
188
-
189
- ::: warning
190
- This will not mock modules that were imported before this was called. Don't forget that all static imports in ESM are always [hoisted](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#hoisting), so putting this before static import will not force it to be called before the import:
191
-
192
- ```ts
193
- vi.doMock('./increment.js') // this will be called _after_ the import statement
194
-
195
- import { increment } from './increment.js'
196
- ```
197
- :::
198
-
199
- ```ts [increment.js]
200
- export function increment(number) {
201
- return number + 1
202
- }
203
- ```
204
-
205
- ```ts [increment.test.js]
206
- import { beforeEach, test } from 'vitest'
207
- import { increment } from './increment.js'
208
-
209
- // the module is not mocked, because vi.doMock is not called yet
210
- increment(1) === 2
211
-
212
- let mockedIncrement = 100
213
-
214
- beforeEach(() => {
215
- // you can access variables inside a factory
216
- vi.doMock('./increment.js', () => ({ increment: () => ++mockedIncrement }))
217
- })
218
-
219
- test('importing the next module imports mocked one', async () => {
220
- // original import WAS NOT MOCKED, because vi.doMock is evaluated AFTER imports
221
- expect(increment(1)).toBe(2)
222
- const { increment: mockedIncrement } = await import('./increment.js')
223
- // new dynamic import returns mocked module
224
- expect(mockedIncrement(1)).toBe(101)
225
- expect(mockedIncrement(1)).toBe(102)
226
- expect(mockedIncrement(1)).toBe(103)
227
- })
228
- ```
229
-
230
- ::: tip
231
- In environments that support [Explicit Resource Management](https://github.com/tc39/proposal-explicit-resource-management), you can use `using` on the value returned from `vi.doMock()` to automatically call [`vi.doUnmock()`](#vi-dounmock) on the mocked module when the containing block is exited. This is especially useful when mocking a dynamically imported module for a single test case.
232
-
233
- ```ts
234
- it('uses a mocked version of my-module', () => {
235
- using _mockDisposable = vi.doMock('my-module')
236
-
237
- const myModule = await import('my-module') // mocked
238
-
239
- // my-module is restored here
240
- })
241
-
242
- it('uses the normal version of my-module again', () => {
243
- const myModule = await import('my-module') // not mocked
244
- })
245
- ```
246
- :::
247
-
248
- ### vi.mocked
249
-
250
- ```ts
251
- function mocked<T>(
252
- object: T,
253
- deep?: boolean
254
- ): MaybeMockedDeep<T>
255
- function mocked<T>(
256
- object: T,
257
- options?: { partial?: boolean; deep?: boolean }
258
- ): MaybePartiallyMockedDeep<T>
259
- ```
260
-
261
- Type helper for TypeScript. Just returns the object that was passed.
262
-
263
- When `partial` is `true` it will expect a `Partial<T>` as a return value. By default, this will only make TypeScript believe that the first level values are mocked. You can pass down `{ deep: true }` as a second argument to tell TypeScript that the whole object is mocked, if it actually is. You can pass down `{ partial: true, deep: true }` to make nested objects also partial recursively.
264
-
265
- ```ts [example.ts]
266
- export function add(x: number, y: number): number {
267
- return x + y
268
- }
269
-
270
- export function fetchSomething(): Promise<Response> {
271
- return fetch('https://vitest.dev/')
272
- }
273
-
274
- export function getUser(): { name: string; address: { city: string; zip: string } } {
275
- return { name: 'John', address: { city: 'New York', zip: '10001' } }
276
- }
277
- ```
278
-
279
- ```ts [example.test.ts]
280
- import * as example from './example'
281
-
282
- vi.mock('./example')
283
-
284
- test('1 + 1 equals 10', async () => {
285
- vi.mocked(example.add).mockReturnValue(10)
286
- expect(example.add(1, 1)).toBe(10)
287
- })
288
-
289
- test('mock return value with only partially correct typing', async () => {
290
- vi.mocked(example.fetchSomething).mockResolvedValue(new Response('hello'))
291
- vi.mocked(example.fetchSomething, { partial: true }).mockResolvedValue({ ok: false })
292
- // vi.mocked(example.someFn).mockResolvedValue({ ok: false }) // this is a type error
293
- })
294
-
295
- test('mock return value with deep partial typing', async () => {
296
- vi.mocked(example.getUser, { partial: true, deep: true }).mockReturnValue({
297
- address: { city: 'Los Angeles' },
298
- })
299
- expect(example.getUser().address.city).toBe('Los Angeles')
300
- })
301
- ```
302
-
303
- ### vi.importActual
304
-
305
- ```ts
306
- function importActual<T>(path: string): Promise<T>
307
- ```
308
-
309
- Imports module, bypassing all checks if it should be mocked. Can be useful if you want to mock module partially.
310
-
311
- ```ts
312
- vi.mock('./example.js', async () => {
313
- const originalModule = await vi.importActual('./example.js')
314
-
315
- return { ...originalModule, get: vi.fn() }
316
- })
317
- ```
318
-
319
- ### vi.importMock
320
-
321
- ```ts
322
- function importMock<T>(path: string): Promise<MaybeMockedDeep<T>>
323
- ```
324
-
325
- Imports a module with all of its properties (including nested properties) mocked. Follows the same rules that [`vi.mock`](#vi-mock) does. For the rules applied, see [algorithm](/guide/mocking/modules#automocking-algorithm).
326
-
327
- ### vi.unmock
328
-
329
- ```ts
330
- function unmock(path: string | Promise<Module>): void
331
- ```
332
-
333
- Removes module from the mocked registry. All calls to import will return the original module even if it was mocked before. This call is hoisted to the top of the file, so it will only unmock modules that were defined in `setupFiles`, for example.
334
-
335
- ### vi.doUnmock
336
-
337
- ```ts
338
- function doUnmock(path: string | Promise<Module>): void
339
- ```
340
-
341
- The same as [`vi.unmock`](#vi-unmock), but is not hoisted to the top of the file. The next import of the module will import the original module instead of the mock. This will not unmock previously imported modules.
342
-
343
- ```ts [increment.js]
344
- export function increment(number) {
345
- return number + 1
346
- }
347
- ```
348
-
349
- ```ts [increment.test.js]
350
- import { increment } from './increment.js'
351
-
352
- // increment is already mocked, because vi.mock is hoisted
353
- increment(1) === 100
354
-
355
- // this is hoisted, and factory is called before the import on line 1
356
- vi.mock('./increment.js', () => ({ increment: () => 100 }))
357
-
358
- // all calls are mocked, and `increment` always returns 100
359
- increment(1) === 100
360
- increment(30) === 100
361
-
362
- // this is not hoisted, so other import will return unmocked module
363
- vi.doUnmock('./increment.js')
364
-
365
- // this STILL returns 100, because `vi.doUnmock` doesn't reevaluate a module
366
- increment(1) === 100
367
- increment(30) === 100
368
-
369
- // the next import is unmocked, now `increment` is the original function that returns count + 1
370
- const { increment: unmockedIncrement } = await import('./increment.js')
371
-
372
- unmockedIncrement(1) === 2
373
- unmockedIncrement(30) === 31
374
- ```
375
-
376
- ### vi.resetModules
377
-
378
- ```ts
379
- function resetModules(): Vitest
380
- ```
381
-
382
- Resets modules registry by clearing the cache of all modules. This allows modules to be reevaluated when reimported. Top-level imports cannot be re-evaluated. Might be useful to isolate modules where local state conflicts between tests.
383
-
384
- ```ts
385
- import { vi } from 'vitest'
386
-
387
- import { data } from './data.js' // Will not get reevaluated beforeEach test
388
-
389
- beforeEach(() => {
390
- vi.resetModules()
391
- })
392
-
393
- test('change state', async () => {
394
- const mod = await import('./some/path.js') // Will get reevaluated
395
- mod.changeLocalState('new value')
396
- expect(mod.getLocalState()).toBe('new value')
397
- })
398
-
399
- test('module has old state', async () => {
400
- const mod = await import('./some/path.js') // Will get reevaluated
401
- expect(mod.getLocalState()).toBe('old value')
402
- })
403
- ```
404
-
405
- ::: warning
406
- Does not reset mocks registry. To clear mocks registry, use [`vi.unmock`](#vi-unmock) or [`vi.doUnmock`](#vi-dounmock).
407
- :::
408
-
409
- ### vi.dynamicImportSettled
410
-
411
- ```ts
412
- function dynamicImportSettled(): Promise<void>
413
- ```
414
-
415
- Wait for all imports to load. Useful, if you have a synchronous call that starts importing a module that you cannot wait otherwise.
416
-
417
- ```ts
418
- import { expect, test } from 'vitest'
419
-
420
- // cannot track import because Promise is not returned
421
- function renderComponent() {
422
- import('./component.js').then(({ render }) => {
423
- render()
424
- })
425
- }
426
-
427
- test('operations are resolved', async () => {
428
- renderComponent()
429
- await vi.dynamicImportSettled()
430
- expect(document.querySelector('.component')).not.toBeNull()
431
- })
432
- ```
433
-
434
- ::: tip
435
- If during a dynamic import another dynamic import is initiated, this method will wait until all of them are resolved.
436
-
437
- This method will also wait for the next `setTimeout` tick after the import is resolved so all synchronous operations should be completed by the time it's resolved.
438
- :::
439
-
440
- ## Mocking Functions and Objects
441
-
442
- This section describes how to work with [method mocks](/api/mock) and replace environmental and global variables.
443
-
444
- ### vi.fn
445
-
446
- ```ts
447
- function fn(fn?: Procedure | Constructable): Mock
448
- ```
449
-
450
- Creates a spy on a function, but can also be initiated without one. Every time a function is invoked, it stores its call arguments, returns, and instances. Additionally, you can manipulate its behavior with [methods](/api/mock).
451
- If no function is given, mock will return `undefined` when invoked.
452
-
453
- ```ts
454
- const getApples = vi.fn(() => 0)
455
-
456
- getApples()
457
-
458
- expect(getApples).toHaveBeenCalled()
459
- expect(getApples).toHaveReturnedWith(0)
460
-
461
- getApples.mockReturnValueOnce(5)
462
-
463
- const res = getApples()
464
- expect(res).toBe(5)
465
- expect(getApples).toHaveNthReturnedWith(2, 5)
466
- ```
467
-
468
- You can also pass down a class to `vi.fn`:
469
-
470
- ```ts
471
- const Cart = vi.fn(class {
472
- get = () => 0
473
- })
474
-
475
- const cart = new Cart()
476
- expect(Cart).toHaveBeenCalled()
477
- ```
478
-
479
- ### vi.mockObject <Version>3.2.0</Version>
480
-
481
- ```ts
482
- function mockObject<T>(value: T, options?: MockOptions): MaybeMockedDeep<T>
483
- ```
484
-
485
- Deeply mocks properties and methods of a given object in the same way as `vi.mock()` mocks module exports. See [automocking](/guide/mocking.html#automocking-algorithm) for the detail.
486
-
487
- ```ts
488
- const original = {
489
- simple: () => 'value',
490
- nested: {
491
- method: () => 'real'
492
- },
493
- prop: 'foo',
494
- }
495
-
496
- const mocked = vi.mockObject(original)
497
- expect(mocked.simple()).toBe(undefined)
498
- expect(mocked.nested.method()).toBe(undefined)
499
- expect(mocked.prop).toBe('foo')
500
-
501
- mocked.simple.mockReturnValue('mocked')
502
- mocked.nested.method.mockReturnValue('mocked nested')
503
-
504
- expect(mocked.simple()).toBe('mocked')
505
- expect(mocked.nested.method()).toBe('mocked nested')
506
- ```
507
-
508
- Just like `vi.mock()`, you can pass `{ spy: true }` as a second argument to keep function implementations:
509
-
510
- ```ts
511
- const spied = vi.mockObject(original, { spy: true })
512
- expect(spied.simple()).toBe('value')
513
- expect(spied.simple).toHaveBeenCalled()
514
- expect(spied.simple.mock.results[0]).toEqual({ type: 'return', value: 'value' })
515
- ```
516
-
517
- ### vi.isMockFunction
518
-
519
- ```ts
520
- function isMockFunction(fn: unknown): asserts fn is Mock
521
- ```
522
-
523
- Checks that a given parameter is a mock function. If you are using TypeScript, it will also narrow down its type.
524
-
525
- ### vi.clearAllMocks
526
-
527
- ```ts
528
- function clearAllMocks(): Vitest
529
- ```
530
-
531
- Calls [`.mockClear()`](/api/mock#mockclear) on all spies.
532
- This will clear mock history without affecting mock implementations.
533
-
534
- ### vi.resetAllMocks
535
-
536
- ```ts
537
- function resetAllMocks(): Vitest
538
- ```
539
-
540
- Calls [`.mockReset()`](/api/mock#mockreset) on all spies.
541
- This will clear mock history and reset each mock's implementation.
542
-
543
- ### vi.restoreAllMocks
544
-
545
- ```ts
546
- function restoreAllMocks(): Vitest
547
- ```
548
-
549
- This restores all original implementations on spies created with [`vi.spyOn`](#vi-spyon).
550
-
551
- After the mock was restored, you can spy on it again.
552
-
553
- ::: warning
554
- This method also does not affect mocks created during [automocking](/guide/mocking/modules#mocking-a-module).
555
-
556
- Note that unlike [`mock.mockRestore`](/api/mock#mockrestore), `vi.restoreAllMocks` will not clear mock history or reset the mock implementation
557
- :::
558
-
559
- ### vi.spyOn
560
-
561
- ```ts
562
- function spyOn<T, K extends keyof T>(
563
- object: T,
564
- key: K,
565
- accessor?: 'get' | 'set'
566
- ): Mock<T[K]>
567
- ```
568
-
569
- Creates a spy on a method or getter/setter of an object similar to [`vi.fn()`](#vi-fn). It returns a [mock function](/api/mock).
570
-
571
- ```ts
572
- let apples = 0
573
- const cart = {
574
- getApples: () => 42,
575
- }
576
-
577
- const spy = vi.spyOn(cart, 'getApples').mockImplementation(() => apples)
578
- apples = 1
579
-
580
- expect(cart.getApples()).toBe(1)
581
-
582
- expect(spy).toHaveBeenCalled()
583
- expect(spy).toHaveReturnedWith(1)
584
- ```
585
-
586
- If the spying method is a class definition, the mock implementations have to use the `function` or the `class` keyword:
587
-
588
- ```ts {12-14,16-20}
589
- const cart = {
590
- Apples: class Apples {
591
- getApples() {
592
- return 42
593
- }
594
- }
595
- }
596
-
597
- const spy = vi.spyOn(cart, 'Apples')
598
- .mockImplementation(() => ({ getApples: () => 0 })) // [!code --]
599
- // with a function keyword
600
- .mockImplementation(function () {
601
- this.getApples = () => 0
602
- })
603
- // with a custom class
604
- .mockImplementation(class MockApples {
605
- getApples() {
606
- return 0
607
- }
608
- })
609
- ```
610
-
611
- If you provide an arrow function, you will get [`<anonymous> is not a constructor` error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_constructor) when the mock is called.
612
-
613
- ::: tip
614
- In environments that support [Explicit Resource Management](https://github.com/tc39/proposal-explicit-resource-management), you can use `using` instead of `const` to automatically call `mockRestore` on any mocked function when the containing block is exited. This is especially useful for spied methods:
615
-
616
- ```ts
617
- it('calls console.log', () => {
618
- using spy = vi.spyOn(console, 'log').mockImplementation(() => {})
619
- debug('message')
620
- expect(spy).toHaveBeenCalled()
621
- })
622
- // console.log is restored here
623
- ```
624
- :::
625
-
626
- ::: tip
627
- You can call [`vi.restoreAllMocks`](#vi-restoreallmocks) inside [`afterEach`](/api/hooks#aftereach) (or enable [`test.restoreMocks`](/config/restoremocks)) to restore all methods to their original implementations after every test. This will restore the original [object descriptor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty), so you won't be able to change method's implementation anymore, unless you spy again:
628
-
629
- ```ts
630
- const cart = {
631
- getApples: () => 42,
632
- }
633
-
634
- const spy = vi.spyOn(cart, 'getApples').mockReturnValue(10)
635
-
636
- console.log(cart.getApples()) // 10
637
- vi.restoreAllMocks()
638
- console.log(cart.getApples()) // 42
639
- spy.mockReturnValue(10)
640
- console.log(cart.getApples()) // still 42!
641
- ```
642
- :::
643
-
644
- ::: tip
645
- It is not possible to spy on exported methods in [Browser Mode](/guide/browser/). Instead, you can spy on every exported method by calling `vi.mock("./file-path.js", { spy: true })`. This will mock every export but keep its implementation intact, allowing you to assert if the method was called correctly.
646
-
647
- ```ts
648
- import { calculator } from './src/calculator.ts'
649
-
650
- vi.mock('./src/calculator.ts', { spy: true })
651
-
652
- calculator(1, 2)
653
-
654
- expect(calculator).toHaveBeenCalledWith(1, 2)
655
- expect(calculator).toHaveReturned(3)
656
- ```
657
-
658
- And while it is possible to spy on exports in `jsdom` or other Node.js environments, this might change in the future.
659
- :::
660
-
661
- ### vi.stubEnv {#vi-stubenv}
662
-
663
- ```ts
664
- function stubEnv<T extends string>(
665
- name: T,
666
- value: T extends 'PROD' | 'DEV' | 'SSR' ? boolean : string | undefined
667
- ): Vitest
668
- ```
669
-
670
- Changes the value of environmental variable on `process.env` and `import.meta.env`. You can restore its value by calling `vi.unstubAllEnvs`.
671
-
672
- ```ts
673
- import { vi } from 'vitest'
674
-
675
- // `process.env.NODE_ENV` and `import.meta.env.NODE_ENV`
676
- // are "development" before calling "vi.stubEnv"
677
-
678
- vi.stubEnv('NODE_ENV', 'production')
679
-
680
- process.env.NODE_ENV === 'production'
681
- import.meta.env.NODE_ENV === 'production'
682
-
683
- vi.stubEnv('NODE_ENV', undefined)
684
-
685
- process.env.NODE_ENV === undefined
686
- import.meta.env.NODE_ENV === undefined
687
-
688
- // doesn't change other envs
689
- import.meta.env.MODE === 'development'
690
- ```
691
-
692
- :::tip
693
- You can also change the value by simply assigning it, but you won't be able to use `vi.unstubAllEnvs` to restore previous value:
694
-
695
- ```ts
696
- import.meta.env.MODE = 'test'
697
- ```
698
- :::
699
-
700
- ### vi.unstubAllEnvs {#vi-unstuballenvs}
701
-
702
- ```ts
703
- function unstubAllEnvs(): Vitest
704
- ```
705
-
706
- Restores all `import.meta.env` and `process.env` values that were changed with `vi.stubEnv`. When it's called for the first time, Vitest remembers the original value and will store it, until `unstubAllEnvs` is called again.
707
-
708
- ```ts
709
- import { vi } from 'vitest'
710
-
711
- // `process.env.NODE_ENV` and `import.meta.env.NODE_ENV`
712
- // are "development" before calling stubEnv
713
-
714
- vi.stubEnv('NODE_ENV', 'production')
715
-
716
- process.env.NODE_ENV === 'production'
717
- import.meta.env.NODE_ENV === 'production'
718
-
719
- vi.stubEnv('NODE_ENV', 'staging')
720
-
721
- process.env.NODE_ENV === 'staging'
722
- import.meta.env.NODE_ENV === 'staging'
723
-
724
- vi.unstubAllEnvs()
725
-
726
- // restores to the value that were stored before the first "stubEnv" call
727
- process.env.NODE_ENV === 'development'
728
- import.meta.env.NODE_ENV === 'development'
729
- ```
730
-
731
- ### vi.stubGlobal
732
-
733
- ```ts
734
- function stubGlobal(
735
- name: string | number | symbol,
736
- value: unknown
737
- ): Vitest
738
- ```
739
-
740
- Changes the value of global variable. You can restore its original value by calling `vi.unstubAllGlobals`.
741
-
742
- ```ts
743
- import { vi } from 'vitest'
744
-
745
- // `innerWidth` is "0" before calling stubGlobal
746
-
747
- vi.stubGlobal('innerWidth', 100)
748
-
749
- innerWidth === 100
750
- globalThis.innerWidth === 100
751
- // if you are using jsdom or happy-dom
752
- window.innerWidth === 100
753
- ```
754
-
755
- :::tip
756
- You can also change the value by simply assigning it to `globalThis` or `window` (if you are using `jsdom` or `happy-dom` environment), but you won't be able to use `vi.unstubAllGlobals` to restore original value:
757
-
758
- ```ts
759
- globalThis.innerWidth = 100
760
- // if you are using jsdom or happy-dom
761
- window.innerWidth = 100
762
- ```
763
- :::
764
-
765
- ### vi.unstubAllGlobals {#vi-unstuballglobals}
766
-
767
- ```ts
768
- function unstubAllGlobals(): Vitest
769
- ```
770
-
771
- Restores all global values on `globalThis`/`global` (and `window`/`top`/`self`/`parent`, if you are using `jsdom` or `happy-dom` environment) that were changed with `vi.stubGlobal`. When it's called for the first time, Vitest remembers the original value and will store it, until `unstubAllGlobals` is called again.
772
-
773
- ```ts
774
- import { vi } from 'vitest'
775
-
776
- const Mock = vi.fn()
777
-
778
- // IntersectionObserver is "undefined" before calling "stubGlobal"
779
-
780
- vi.stubGlobal('IntersectionObserver', Mock)
781
-
782
- IntersectionObserver === Mock
783
- global.IntersectionObserver === Mock
784
- globalThis.IntersectionObserver === Mock
785
- // if you are using jsdom or happy-dom
786
- window.IntersectionObserver === Mock
787
-
788
- vi.unstubAllGlobals()
789
-
790
- globalThis.IntersectionObserver === undefined
791
- 'IntersectionObserver' in globalThis === false
792
- // throws ReferenceError, because it's not defined
793
- IntersectionObserver === undefined
794
- ```
795
-
796
- ## Fake Timers
797
-
798
- This sections describes how to work with [fake timers](/guide/mocking/timers).
799
-
800
- ### vi.advanceTimersByTime
801
-
802
- ```ts
803
- function advanceTimersByTime(ms: number): Vitest
804
- ```
805
-
806
- This method will invoke every initiated timer until the specified number of milliseconds is passed or the queue is empty - whatever comes first.
807
-
808
- ```ts
809
- let i = 0
810
- setInterval(() => console.log(++i), 50)
811
-
812
- vi.advanceTimersByTime(150)
813
-
814
- // log: 1
815
- // log: 2
816
- // log: 3
817
- ```
818
-
819
- ### vi.advanceTimersByTimeAsync
820
-
821
- ```ts
822
- function advanceTimersByTimeAsync(ms: number): Promise<Vitest>
823
- ```
824
-
825
- This method will invoke every initiated timer until the specified number of milliseconds is passed or the queue is empty - whatever comes first. This will include asynchronously set timers.
826
-
827
- ```ts
828
- let i = 0
829
- setInterval(() => Promise.resolve().then(() => console.log(++i)), 50)
830
-
831
- await vi.advanceTimersByTimeAsync(150)
832
-
833
- // log: 1
834
- // log: 2
835
- // log: 3
836
- ```
837
-
838
- ### vi.advanceTimersToNextTimer
839
-
840
- ```ts
841
- function advanceTimersToNextTimer(): Vitest
842
- ```
843
-
844
- Will call next available timer. Useful to make assertions between each timer call. You can chain call it to manage timers by yourself.
845
-
846
- ```ts
847
- let i = 0
848
- setInterval(() => console.log(++i), 50)
849
-
850
- vi.advanceTimersToNextTimer() // log: 1
851
- .advanceTimersToNextTimer() // log: 2
852
- .advanceTimersToNextTimer() // log: 3
853
- ```
854
-
855
- ### vi.advanceTimersToNextTimerAsync
856
-
857
- ```ts
858
- function advanceTimersToNextTimerAsync(): Promise<Vitest>
859
- ```
860
-
861
- Will call next available timer and wait until it's resolved if it was set asynchronously. Useful to make assertions between each timer call.
862
-
863
- ```ts
864
- let i = 0
865
- setInterval(() => Promise.resolve().then(() => console.log(++i)), 50)
866
-
867
- await vi.advanceTimersToNextTimerAsync() // log: 1
868
- expect(console.log).toHaveBeenCalledWith(1)
869
-
870
- await vi.advanceTimersToNextTimerAsync() // log: 2
871
- await vi.advanceTimersToNextTimerAsync() // log: 3
872
- ```
873
-
874
- ### vi.advanceTimersToNextFrame {#vi-advancetimerstonextframe}
875
-
876
- ```ts
877
- function advanceTimersToNextFrame(): Vitest
878
- ```
879
-
880
- Similar to [`vi.advanceTimersByTime`](/api/vi#vi-advancetimersbytime), but will advance timers by the milliseconds needed to execute callbacks currently scheduled with `requestAnimationFrame`.
881
-
882
- ```ts
883
- let frameRendered = false
884
-
885
- requestAnimationFrame(() => {
886
- frameRendered = true
887
- })
888
-
889
- vi.advanceTimersToNextFrame()
890
-
891
- expect(frameRendered).toBe(true)
892
- ```
893
-
894
- ### vi.getTimerCount
895
-
896
- ```ts
897
- function getTimerCount(): number
898
- ```
899
-
900
- Get the number of waiting timers.
901
-
902
- ### vi.clearAllTimers
903
-
904
- ```ts
905
- function clearAllTimers(): void
906
- ```
907
-
908
- Removes all timers that are scheduled to run. These timers will never run in the future.
909
-
910
- ### vi.getMockedSystemTime
911
-
912
- ```ts
913
- function getMockedSystemTime(): Date | null
914
- ```
915
-
916
- Returns mocked current date. If date is not mocked the method will return `null`.
917
-
918
- ### vi.getRealSystemTime
919
-
920
- ```ts
921
- function getRealSystemTime(): number
922
- ```
923
-
924
- When using `vi.useFakeTimers`, `Date.now` calls are mocked. If you need to get real time in milliseconds, you can call this function.
925
-
926
- ### vi.runAllTicks
927
-
928
- ```ts
929
- function runAllTicks(): Vitest
930
- ```
931
-
932
- Calls every microtask that was queued by `process.nextTick`. This will also run all microtasks scheduled by themselves.
933
-
934
- ### vi.runAllTimers
935
-
936
- ```ts
937
- function runAllTimers(): Vitest
938
- ```
939
-
940
- This method will invoke every initiated timer until the timer queue is empty. It means that every timer called during `runAllTimers` will be fired. If you have an infinite interval, it will throw after 10 000 tries (can be configured with [`fakeTimers.loopLimit`](/config/faketimers#faketimers-looplimit)).
941
-
942
- ```ts
943
- let i = 0
944
- setTimeout(() => console.log(++i))
945
- const interval = setInterval(() => {
946
- console.log(++i)
947
- if (i === 3) {
948
- clearInterval(interval)
949
- }
950
- }, 50)
951
-
952
- vi.runAllTimers()
953
-
954
- // log: 1
955
- // log: 2
956
- // log: 3
957
- ```
958
-
959
- ### vi.runAllTimersAsync
960
-
961
- ```ts
962
- function runAllTimersAsync(): Promise<Vitest>
963
- ```
964
-
965
- This method will asynchronously invoke every initiated timer until the timer queue is empty. It means that every timer called during `runAllTimersAsync` will be fired even asynchronous timers. If you have an infinite interval,
966
- it will throw after 10 000 tries (can be configured with [`fakeTimers.loopLimit`](/config/faketimers#faketimers-looplimit)).
967
-
968
- ```ts
969
- setTimeout(async () => {
970
- console.log(await Promise.resolve('result'))
971
- }, 100)
972
-
973
- await vi.runAllTimersAsync()
974
-
975
- // log: result
976
- ```
977
-
978
- ### vi.runOnlyPendingTimers
979
-
980
- ```ts
981
- function runOnlyPendingTimers(): Vitest
982
- ```
983
-
984
- This method will call every timer that was initiated after [`vi.useFakeTimers`](#vi-usefaketimers) call. It will not fire any timer that was initiated during its call.
985
-
986
- ```ts
987
- let i = 0
988
- setInterval(() => console.log(++i), 50)
989
-
990
- vi.runOnlyPendingTimers()
991
-
992
- // log: 1
993
- ```
994
-
995
- ### vi.runOnlyPendingTimersAsync
996
-
997
- ```ts
998
- function runOnlyPendingTimersAsync(): Promise<Vitest>
999
- ```
1000
-
1001
- This method will asynchronously call every timer that was initiated after [`vi.useFakeTimers`](#vi-usefaketimers) call, even asynchronous ones. It will not fire any timer that was initiated during its call.
1002
-
1003
- ```ts
1004
- setTimeout(() => {
1005
- console.log(1)
1006
- }, 100)
1007
- setTimeout(() => {
1008
- Promise.resolve().then(() => {
1009
- console.log(2)
1010
- setInterval(() => {
1011
- console.log(3)
1012
- }, 40)
1013
- })
1014
- }, 10)
1015
-
1016
- await vi.runOnlyPendingTimersAsync()
1017
-
1018
- // log: 2
1019
- // log: 3
1020
- // log: 3
1021
- // log: 1
1022
- ```
1023
-
1024
- ### vi.setSystemTime
1025
-
1026
- ```ts
1027
- function setSystemTime(date: string | number | Date): Vitest
1028
- ```
1029
-
1030
- If fake timers are enabled, this method simulates a user changing the system clock (will affect date related API like `hrtime`, `performance.now` or `new Date()`) - however, it will not fire any timers. If fake timers are not enabled, this method will only mock `Date.*` calls.
1031
-
1032
- Useful if you need to test anything that depends on the current date - for example [Luxon](https://github.com/moment/luxon/) calls inside your code.
1033
-
1034
- Accepts the same string and number arguments as the `Date`.
1035
-
1036
- ```ts
1037
- const date = new Date(1998, 11, 19)
1038
-
1039
- vi.useFakeTimers()
1040
- vi.setSystemTime(date)
1041
-
1042
- expect(Date.now()).toBe(date.valueOf())
1043
-
1044
- vi.useRealTimers()
1045
- ```
1046
-
1047
- ### vi.useFakeTimers
1048
-
1049
- ```ts
1050
- function useFakeTimers(config?: FakeTimerInstallOpts): Vitest
1051
- ```
1052
-
1053
- To enable mocking timers, you need to call this method. It will wrap all further calls to timers (such as `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`, `setImmediate`, `clearImmediate`, and `Date`) until [`vi.useRealTimers()`](#vi-userealtimers) is called.
1054
-
1055
- Mocking `nextTick` is not supported when running Vitest inside `node:child_process` by using `--pool=forks`. NodeJS uses `process.nextTick` internally in `node:child_process` and hangs when it is mocked. Mocking `nextTick` is supported when running Vitest with `--pool=threads`.
1056
-
1057
- The implementation is based internally on [`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers).
1058
-
1059
- ::: tip
1060
- `vi.useFakeTimers()` does not automatically mock `process.nextTick` and `queueMicrotask`.
1061
- But you can enable it by specifying the option in `toFake` argument: `vi.useFakeTimers({ toFake: ['nextTick', 'queueMicrotask'] })`.
1062
- :::
1063
-
1064
- ### vi.setTimerTickMode <Version>4.1.0</Version> {#vi-settimertickmode}
1065
-
1066
- - **Type:** `(mode: 'manual' | 'nextTimerAsync') => Vitest | (mode: 'interval', interval?: number) => Vitest`
1067
-
1068
- Controls how fake timers are advanced.
1069
-
1070
- - `manual`: The default behavior. Timers will only advance when you call one of `vi.advanceTimers...()` methods.
1071
- - `nextTimerAsync`: Timers will be advanced automatically to the next available timer after each macrotask.
1072
- - `interval`: Timers are advanced automatically by a specified interval.
1073
-
1074
- When `mode` is `'interval'`, you can also provide an `interval` in milliseconds.
1075
-
1076
- **Example:**
1077
-
1078
- ```ts
1079
- import { vi } from 'vitest'
1080
-
1081
- vi.useFakeTimers()
1082
-
1083
- // Manual mode (default)
1084
- vi.setTimerTickMode('manual')
1085
-
1086
- let i = 0
1087
- setInterval(() => console.log(++i), 50)
1088
-
1089
- vi.advanceTimersByTime(150) // logs 1, 2, 3
1090
-
1091
- // nextTimerAsync mode
1092
- vi.setTimerTickMode('nextTimerAsync')
1093
-
1094
- // Timers will advance automatically after each macrotask
1095
- await new Promise(resolve => setTimeout(resolve, 150)) // logs 4, 5, 6
1096
-
1097
- // interval mode (default when 'fakeTimers.shouldAdvanceTime' is `true`)
1098
- vi.setTimerTickMode('interval', 50)
1099
-
1100
- // Timers will advance automatically every 50ms
1101
- await new Promise(resolve => setTimeout(resolve, 150)) // logs 7, 8, 9
1102
- ```
1103
-
1104
- ### vi.isFakeTimers {#vi-isfaketimers}
1105
-
1106
- ```ts
1107
- function isFakeTimers(): boolean
1108
- ```
1109
-
1110
- Returns `true` if fake timers are enabled.
1111
-
1112
- ### vi.useRealTimers
1113
-
1114
- ```ts
1115
- function useRealTimers(): Vitest
1116
- ```
1117
-
1118
- When timers have run out, you may call this method to return mocked timers to its original implementations. All timers that were scheduled before will be discarded.
1119
-
1120
- ## Miscellaneous
1121
-
1122
- A set of useful helper functions that Vitest provides.
1123
-
1124
- ### vi.waitFor {#vi-waitfor}
1125
-
1126
- ```ts
1127
- function waitFor<T>(
1128
- callback: WaitForCallback<T>,
1129
- options?: number | WaitForOptions
1130
- ): Promise<T>
1131
- ```
1132
-
1133
- Wait for the callback to execute successfully. If the callback throws an error or returns a rejected promise it will continue to wait until it succeeds or times out.
1134
-
1135
- If options is set to a number, the effect is equivalent to setting `{ timeout: options }`.
1136
-
1137
- This is very useful when you need to wait for some asynchronous action to complete, for example, when you start a server and need to wait for it to start.
1138
-
1139
- ```ts
1140
- import { expect, test, vi } from 'vitest'
1141
- import { createServer } from './server.js'
1142
-
1143
- test('Server started successfully', async () => {
1144
- const server = createServer()
1145
-
1146
- await vi.waitFor(
1147
- () => {
1148
- if (!server.isReady) {
1149
- throw new Error('Server not started')
1150
- }
1151
-
1152
- console.log('Server started')
1153
- },
1154
- {
1155
- timeout: 500, // default is 1000
1156
- interval: 20, // default is 50
1157
- }
1158
- )
1159
- expect(server.isReady).toBe(true)
1160
- })
1161
- ```
1162
-
1163
- It also works for asynchronous callbacks
1164
-
1165
- ```ts
1166
- // @vitest-environment jsdom
1167
-
1168
- import { expect, test, vi } from 'vitest'
1169
- import { getDOMElementAsync, populateDOMAsync } from './dom.js'
1170
-
1171
- test('Element exists in a DOM', async () => {
1172
- // start populating DOM
1173
- populateDOMAsync()
1174
-
1175
- const element = await vi.waitFor(async () => {
1176
- // try to get the element until it exists
1177
- const element = await getDOMElementAsync() as HTMLElement | null
1178
- expect(element).toBeTruthy()
1179
- expect(element.dataset.initialized).toBeTruthy()
1180
- return element
1181
- }, {
1182
- timeout: 500, // default is 1000
1183
- interval: 20, // default is 50
1184
- })
1185
- expect(element).toBeInstanceOf(HTMLElement)
1186
- })
1187
- ```
1188
-
1189
- If `vi.useFakeTimers` is used, `vi.waitFor` automatically calls `vi.advanceTimersByTime(interval)` in every check callback.
1190
-
1191
- ### vi.waitUntil {#vi-waituntil}
1192
-
1193
- ```ts
1194
- function waitUntil<T>(
1195
- callback: WaitUntilCallback<T>,
1196
- options?: number | WaitUntilOptions
1197
- ): Promise<T>
1198
- ```
1199
-
1200
- This is similar to `vi.waitFor`, but if the callback throws any errors, execution is immediately interrupted and an error message is received. If the callback returns falsy value, the next check will continue until truthy value is returned. This is useful when you need to wait for something to exist before taking the next step.
1201
-
1202
- Look at the example below. We can use `vi.waitUntil` to wait for the element to appear on the page, and then we can do something with the element.
1203
-
1204
- ```ts
1205
- import { expect, test, vi } from 'vitest'
1206
-
1207
- test('Element render correctly', async () => {
1208
- const element = await vi.waitUntil(
1209
- () => document.querySelector('.element'),
1210
- {
1211
- timeout: 500, // default is 1000
1212
- interval: 20, // default is 50
1213
- }
1214
- )
1215
-
1216
- // do something with the element
1217
- expect(element.querySelector('.element-child')).toBeTruthy()
1218
- })
1219
- ```
1220
-
1221
- ### vi.hoisted {#vi-hoisted}
1222
-
1223
- ```ts
1224
- function hoisted<T>(factory: () => T): T
1225
- ```
1226
-
1227
- All static `import` statements in ES modules are hoisted to the top of the file, so any code that is defined before the imports will actually be executed after imports are evaluated.
1228
-
1229
- However, it can be useful to invoke some side effects like mocking dates before importing a module.
1230
-
1231
- To bypass this limitation, you can rewrite static imports into dynamic ones like this:
1232
-
1233
- ```diff
1234
- callFunctionWithSideEffect()
1235
- - import { value } from './some/module.js'
1236
- + const { value } = await import('./some/module.js')
1237
- ```
1238
-
1239
- When running `vitest`, you can do this automatically by using `vi.hoisted` method. Under the hood, Vitest will convert static imports into dynamic ones with preserved live-bindings.
1240
-
1241
- ```diff
1242
- - callFunctionWithSideEffect()
1243
- import { value } from './some/module.js'
1244
- + vi.hoisted(() => callFunctionWithSideEffect())
1245
- ```
1246
-
1247
- ::: warning IMPORTS ARE NOT AVAILABLE
1248
- Running code before the imports means that you cannot access imported variables because they are not defined yet:
1249
-
1250
- ```ts
1251
- import { value } from './some/module.js'
1252
-
1253
- vi.hoisted(() => { value }) // throws an error // [!code warning]
1254
- ```
1255
-
1256
- This code will produce an error:
1257
-
1258
- ```
1259
- Cannot access '__vi_import_0__' before initialization
1260
- ```
1261
-
1262
- If you need to access a variable from another module inside of `vi.hoisted`, use dynamic import:
1263
-
1264
- ```ts
1265
- await vi.hoisted(async () => {
1266
- const { value } = await import('./some/module.js')
1267
- })
1268
- ```
1269
-
1270
- However, it is discourage to import anything inside of `vi.hoisted` because imports are already hoisted - if you need to execute something before the tests are running, just execute it in the imported module itself.
1271
- :::
1272
-
1273
- This method returns the value that was returned from the factory. You can use that value in your `vi.mock` factories if you need easy access to locally defined variables:
1274
-
1275
- ```ts
1276
- import { expect, vi } from 'vitest'
1277
- import { originalMethod } from './path/to/module.js'
1278
-
1279
- const { mockedMethod } = vi.hoisted(() => {
1280
- return { mockedMethod: vi.fn() }
1281
- })
1282
-
1283
- vi.mock('./path/to/module.js', () => {
1284
- return { originalMethod: mockedMethod }
1285
- })
1286
-
1287
- mockedMethod.mockReturnValue(100)
1288
- expect(originalMethod()).toBe(100)
1289
- ```
1290
-
1291
- Note that this method can also be called asynchronously even if your environment doesn't support top-level await:
1292
-
1293
- ```ts
1294
- const json = await vi.hoisted(async () => {
1295
- const response = await fetch('https://jsonplaceholder.typicode.com/posts')
1296
- return response.json()
1297
- })
1298
- ```
1299
-
1300
- ### vi.setConfig
1301
-
1302
- ```ts
1303
- function setConfig(config: RuntimeOptions): void
1304
- ```
1305
-
1306
- Updates config for the current test file. This method supports only config options that will affect the current test file:
1307
-
1308
- ```ts
1309
- vi.setConfig({
1310
- allowOnly: true,
1311
- testTimeout: 10_000,
1312
- hookTimeout: 10_000,
1313
- clearMocks: true,
1314
- restoreMocks: true,
1315
- fakeTimers: {
1316
- now: new Date(2021, 11, 19),
1317
- // supports the whole object
1318
- },
1319
- maxConcurrency: 10,
1320
- sequence: {
1321
- hooks: 'stack'
1322
- // supports only "sequence.hooks"
1323
- }
1324
- })
1325
- ```
1326
-
1327
- ### vi.resetConfig
1328
-
1329
- ```ts
1330
- function resetConfig(): void
1331
- ```
1332
-
1333
- If [`vi.setConfig`](#vi-setconfig) was called before, this will reset config to the original state.
1334
-
1335
- ### vi.defineHelper <Version>4.1.0</Version> {#vi-defineHelper}
1336
-
1337
- ```ts
1338
- function defineHelper<F extends (...args: any) => any>(fn: F): F
1339
- ```
1340
-
1341
- Wraps a function to create an assertion helper. When an assertion fails inside the helper, the error stack trace will point to where the helper was called, not inside the helper itself. This makes it easier to identify the source of test failures when using custom assertion functions.
1342
-
1343
- Works with both synchronous and asynchronous functions, and supports `expect.soft()`.
1344
-
1345
- ```ts
1346
- import { expect, vi } from 'vitest'
1347
-
1348
- const assertPair = vi.defineHelper((a, b) => {
1349
- expect(a).toEqual(b)
1350
- })
1351
-
1352
- test('example', () => {
1353
- assertPair('left', 'right') // Error points to this line
1354
- })
1355
- ```
1356
-
1357
- Example output:
1358
-
1359
- <!-- eslint-skip -->
1360
- ```js
1361
- FAIL example.test.ts > example
1362
- AssertionError: expected 'left' to deeply equal 'right'
1363
-
1364
- Expected: "right"
1365
- Received: "left"
1366
-
1367
- ❯ example.test.ts:8:3
1368
- 7| test('example', () => {
1369
- 8| assertPair('left', 'right')
1370
- | ^
1371
- 9| })
1372
- ```