@vitest-agent/mcp 1.0.1 → 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 (229) hide show
  1. package/README.md +1 -2
  2. package/bin/vitest-agent-mcp.js +1 -17
  3. package/index.d.ts +324 -315
  4. package/index.js +2 -4
  5. package/middleware/idempotency.js +1 -1
  6. package/package.json +2 -2
  7. package/server.js +2 -4
  8. package/tools/acceptance-metrics.js +1 -1
  9. package/tools/cache-health.js +1 -1
  10. package/tools/commit-changes.js +1 -1
  11. package/tools/configure.js +1 -1
  12. package/tools/coverage.js +1 -1
  13. package/tools/errors.js +1 -1
  14. package/tools/failure-signature-get.js +1 -1
  15. package/tools/file-coverage.js +1 -1
  16. package/tools/history.js +1 -1
  17. package/tools/inventory.js +1 -1
  18. package/tools/overview.js +1 -1
  19. package/tools/run-tests.js +15 -3
  20. package/tools/settings-list.js +1 -1
  21. package/tools/status.js +1 -1
  22. package/tools/tdd-artifact.js +1 -1
  23. package/tools/tdd-task.js +1 -1
  24. package/tools/test.js +1 -1
  25. package/tools/trends.js +1 -1
  26. package/tools/turn-search.js +1 -1
  27. package/public/patterns/_meta.json +0 -67
  28. package/public/patterns/authoring-a-custom-vitest-agent-reporter.md +0 -82
  29. package/public/patterns/known-issues-and-caveats.md +0 -52
  30. package/public/patterns/operating-vitest-agent-as-an-agent.md +0 -53
  31. package/public/patterns/running-tests-via-mcp.md +0 -58
  32. package/public/patterns/silencing-leaking-output-in-tests.md +0 -91
  33. package/public/patterns/testing-effect-schema-definitions.md +0 -71
  34. package/public/patterns/testing-effect-services-with-mock-layers.md +0 -63
  35. package/public/vendor/vitest-docs/ATTRIBUTION.md +0 -5
  36. package/public/vendor/vitest-docs/api/advanced/artifacts.md +0 -189
  37. package/public/vendor/vitest-docs/api/advanced/metadata.md +0 -68
  38. package/public/vendor/vitest-docs/api/advanced/plugin.md +0 -168
  39. package/public/vendor/vitest-docs/api/advanced/reporters.md +0 -342
  40. package/public/vendor/vitest-docs/api/advanced/runner.md +0 -334
  41. package/public/vendor/vitest-docs/api/advanced/test-case.md +0 -302
  42. package/public/vendor/vitest-docs/api/advanced/test-collection.md +0 -89
  43. package/public/vendor/vitest-docs/api/advanced/test-module.md +0 -140
  44. package/public/vendor/vitest-docs/api/advanced/test-project.md +0 -321
  45. package/public/vendor/vitest-docs/api/advanced/test-specification.md +0 -96
  46. package/public/vendor/vitest-docs/api/advanced/test-suite.md +0 -230
  47. package/public/vendor/vitest-docs/api/advanced/vitest.md +0 -684
  48. package/public/vendor/vitest-docs/api/assert-type.md +0 -22
  49. package/public/vendor/vitest-docs/api/assert.md +0 -1960
  50. package/public/vendor/vitest-docs/api/browser/assertions.md +0 -1277
  51. package/public/vendor/vitest-docs/api/browser/commands.md +0 -154
  52. package/public/vendor/vitest-docs/api/browser/context.md +0 -338
  53. package/public/vendor/vitest-docs/api/browser/interactivity.md +0 -681
  54. package/public/vendor/vitest-docs/api/browser/locators.md +0 -1171
  55. package/public/vendor/vitest-docs/api/browser/react.md +0 -346
  56. package/public/vendor/vitest-docs/api/browser/svelte.md +0 -292
  57. package/public/vendor/vitest-docs/api/browser/vue.md +0 -222
  58. package/public/vendor/vitest-docs/api/describe.md +0 -374
  59. package/public/vendor/vitest-docs/api/expect-typeof.md +0 -571
  60. package/public/vendor/vitest-docs/api/expect.md +0 -2304
  61. package/public/vendor/vitest-docs/api/hooks.md +0 -463
  62. package/public/vendor/vitest-docs/api/mock.md +0 -701
  63. package/public/vendor/vitest-docs/api/test.md +0 -926
  64. package/public/vendor/vitest-docs/api/vi.md +0 -1372
  65. package/public/vendor/vitest-docs/config/alias.md +0 -13
  66. package/public/vendor/vitest-docs/config/allowonly.md +0 -32
  67. package/public/vendor/vitest-docs/config/api.md +0 -27
  68. package/public/vendor/vitest-docs/config/attachmentsdir.md +0 -6
  69. package/public/vendor/vitest-docs/config/bail.md +0 -9
  70. package/public/vendor/vitest-docs/config/benchmark.md +0 -65
  71. package/public/vendor/vitest-docs/config/browser/api.md +0 -23
  72. package/public/vendor/vitest-docs/config/browser/commands.md +0 -6
  73. package/public/vendor/vitest-docs/config/browser/connecttimeout.md +0 -10
  74. package/public/vendor/vitest-docs/config/browser/detailspanelposition.md +0 -38
  75. package/public/vendor/vitest-docs/config/browser/enabled.md +0 -40
  76. package/public/vendor/vitest-docs/config/browser/expect.md +0 -250
  77. package/public/vendor/vitest-docs/config/browser/headless.md +0 -7
  78. package/public/vendor/vitest-docs/config/browser/instances.md +0 -47
  79. package/public/vendor/vitest-docs/config/browser/isolate.md +0 -11
  80. package/public/vendor/vitest-docs/config/browser/locators.md +0 -24
  81. package/public/vendor/vitest-docs/config/browser/orchestratorscripts.md +0 -39
  82. package/public/vendor/vitest-docs/config/browser/playwright.md +0 -214
  83. package/public/vendor/vitest-docs/config/browser/preview.md +0 -32
  84. package/public/vendor/vitest-docs/config/browser/provider.md +0 -79
  85. package/public/vendor/vitest-docs/config/browser/screenshotdirectory.md +0 -6
  86. package/public/vendor/vitest-docs/config/browser/screenshotfailures.md +0 -6
  87. package/public/vendor/vitest-docs/config/browser/testerhtmlpath.md +0 -5
  88. package/public/vendor/vitest-docs/config/browser/trace.md +0 -43
  89. package/public/vendor/vitest-docs/config/browser/trackunhandlederrors.md +0 -10
  90. package/public/vendor/vitest-docs/config/browser/ui.md +0 -7
  91. package/public/vendor/vitest-docs/config/browser/viewport.md +0 -6
  92. package/public/vendor/vitest-docs/config/browser/webdriverio.md +0 -64
  93. package/public/vendor/vitest-docs/config/cache.md +0 -26
  94. package/public/vendor/vitest-docs/config/chaiconfig.md +0 -29
  95. package/public/vendor/vitest-docs/config/clearmocks.md +0 -22
  96. package/public/vendor/vitest-docs/config/coverage.md +0 -455
  97. package/public/vendor/vitest-docs/config/css.md +0 -47
  98. package/public/vendor/vitest-docs/config/dangerouslyignoreunhandlederrors.md +0 -23
  99. package/public/vendor/vitest-docs/config/deps.md +0 -127
  100. package/public/vendor/vitest-docs/config/detectasyncleaks.md +0 -39
  101. package/public/vendor/vitest-docs/config/diff.md +0 -96
  102. package/public/vendor/vitest-docs/config/dir.md +0 -7
  103. package/public/vendor/vitest-docs/config/disableconsoleintercept.md +0 -15
  104. package/public/vendor/vitest-docs/config/env.md +0 -5
  105. package/public/vendor/vitest-docs/config/environment.md +0 -96
  106. package/public/vendor/vitest-docs/config/environmentoptions.md +0 -30
  107. package/public/vendor/vitest-docs/config/exclude.md +0 -49
  108. package/public/vendor/vitest-docs/config/execargv.md +0 -10
  109. package/public/vendor/vitest-docs/config/expandsnapshotdiff.md +0 -7
  110. package/public/vendor/vitest-docs/config/expect.md +0 -38
  111. package/public/vendor/vitest-docs/config/experimental.md +0 -510
  112. package/public/vendor/vitest-docs/config/faketimers.md +0 -51
  113. package/public/vendor/vitest-docs/config/fileparallelism.md +0 -11
  114. package/public/vendor/vitest-docs/config/forcereruntriggers.md +0 -19
  115. package/public/vendor/vitest-docs/config/globals.md +0 -42
  116. package/public/vendor/vitest-docs/config/globalsetup.md +0 -72
  117. package/public/vendor/vitest-docs/config/hideskippedtests.md +0 -7
  118. package/public/vendor/vitest-docs/config/hooktimeout.md +0 -7
  119. package/public/vendor/vitest-docs/config/include-source.md +0 -115
  120. package/public/vendor/vitest-docs/config/include.md +0 -71
  121. package/public/vendor/vitest-docs/config/includetasklocation.md +0 -17
  122. package/public/vendor/vitest-docs/config/index.md +0 -85
  123. package/public/vendor/vitest-docs/config/isolate.md +0 -13
  124. package/public/vendor/vitest-docs/config/logheapusage.md +0 -7
  125. package/public/vendor/vitest-docs/config/maxconcurrency.md +0 -9
  126. package/public/vendor/vitest-docs/config/maxworkers.md +0 -49
  127. package/public/vendor/vitest-docs/config/mockreset.md +0 -22
  128. package/public/vendor/vitest-docs/config/mode.md +0 -7
  129. package/public/vendor/vitest-docs/config/name.md +0 -111
  130. package/public/vendor/vitest-docs/config/onconsolelog.md +0 -25
  131. package/public/vendor/vitest-docs/config/onstacktrace.md +0 -32
  132. package/public/vendor/vitest-docs/config/onunhandlederror.md +0 -35
  133. package/public/vendor/vitest-docs/config/open.md +0 -7
  134. package/public/vendor/vitest-docs/config/outputfile.md +0 -7
  135. package/public/vendor/vitest-docs/config/passwithnotests.md +0 -7
  136. package/public/vendor/vitest-docs/config/pool.md +0 -45
  137. package/public/vendor/vitest-docs/config/printconsoletrace.md +0 -6
  138. package/public/vendor/vitest-docs/config/projects.md +0 -6
  139. package/public/vendor/vitest-docs/config/provide.md +0 -45
  140. package/public/vendor/vitest-docs/config/reporters.md +0 -69
  141. package/public/vendor/vitest-docs/config/resolvesnapshotpath.md +0 -36
  142. package/public/vendor/vitest-docs/config/restoremocks.md +0 -22
  143. package/public/vendor/vitest-docs/config/retry.md +0 -140
  144. package/public/vendor/vitest-docs/config/root.md +0 -6
  145. package/public/vendor/vitest-docs/config/runner.md +0 -6
  146. package/public/vendor/vitest-docs/config/sequence.md +0 -158
  147. package/public/vendor/vitest-docs/config/server.md +0 -68
  148. package/public/vendor/vitest-docs/config/setupfiles.md +0 -40
  149. package/public/vendor/vitest-docs/config/silent.md +0 -9
  150. package/public/vendor/vitest-docs/config/slowtestthreshold.md +0 -7
  151. package/public/vendor/vitest-docs/config/snapshotenvironment.md +0 -27
  152. package/public/vendor/vitest-docs/config/snapshotformat.md +0 -28
  153. package/public/vendor/vitest-docs/config/snapshotserializers.md +0 -6
  154. package/public/vendor/vitest-docs/config/stricttags.md +0 -30
  155. package/public/vendor/vitest-docs/config/tags.md +0 -141
  156. package/public/vendor/vitest-docs/config/teardowntimeout.md +0 -7
  157. package/public/vendor/vitest-docs/config/testnamepattern.md +0 -21
  158. package/public/vendor/vitest-docs/config/testtimeout.md +0 -7
  159. package/public/vendor/vitest-docs/config/typecheck.md +0 -77
  160. package/public/vendor/vitest-docs/config/ui.md +0 -15
  161. package/public/vendor/vitest-docs/config/unstubenvs.md +0 -20
  162. package/public/vendor/vitest-docs/config/unstubglobals.md +0 -20
  163. package/public/vendor/vitest-docs/config/update.md +0 -16
  164. package/public/vendor/vitest-docs/config/vmmemorylimit.md +0 -30
  165. package/public/vendor/vitest-docs/config/watch.md +0 -11
  166. package/public/vendor/vitest-docs/config/watchtriggerpatterns.md +0 -29
  167. package/public/vendor/vitest-docs/guide/advanced/index.md +0 -147
  168. package/public/vendor/vitest-docs/guide/advanced/pool.md +0 -148
  169. package/public/vendor/vitest-docs/guide/advanced/reporters.md +0 -93
  170. package/public/vendor/vitest-docs/guide/advanced/tests.md +0 -125
  171. package/public/vendor/vitest-docs/guide/browser/aria-snapshots.md +0 -470
  172. package/public/vendor/vitest-docs/guide/browser/component-testing.md +0 -571
  173. package/public/vendor/vitest-docs/guide/browser/index.md +0 -630
  174. package/public/vendor/vitest-docs/guide/browser/multiple-setups.md +0 -121
  175. package/public/vendor/vitest-docs/guide/browser/trace-view.md +0 -126
  176. package/public/vendor/vitest-docs/guide/browser/visual-regression-testing.md +0 -734
  177. package/public/vendor/vitest-docs/guide/cli-generated.md +0 -972
  178. package/public/vendor/vitest-docs/guide/cli.md +0 -234
  179. package/public/vendor/vitest-docs/guide/common-errors.md +0 -163
  180. package/public/vendor/vitest-docs/guide/coverage.md +0 -515
  181. package/public/vendor/vitest-docs/guide/debugging.md +0 -127
  182. package/public/vendor/vitest-docs/guide/environment.md +0 -101
  183. package/public/vendor/vitest-docs/guide/extending-matchers.md +0 -160
  184. package/public/vendor/vitest-docs/guide/features.md +0 -310
  185. package/public/vendor/vitest-docs/guide/filtering.md +0 -175
  186. package/public/vendor/vitest-docs/guide/ide.md +0 -43
  187. package/public/vendor/vitest-docs/guide/improving-performance.md +0 -245
  188. package/public/vendor/vitest-docs/guide/in-source.md +0 -159
  189. package/public/vendor/vitest-docs/guide/index.md +0 -128
  190. package/public/vendor/vitest-docs/guide/learn/async.md +0 -147
  191. package/public/vendor/vitest-docs/guide/learn/debugging-tests.md +0 -210
  192. package/public/vendor/vitest-docs/guide/learn/matchers.md +0 -277
  193. package/public/vendor/vitest-docs/guide/learn/mock-functions.md +0 -277
  194. package/public/vendor/vitest-docs/guide/learn/setup-teardown.md +0 -240
  195. package/public/vendor/vitest-docs/guide/learn/snapshots.md +0 -166
  196. package/public/vendor/vitest-docs/guide/learn/testing-in-practice.md +0 -430
  197. package/public/vendor/vitest-docs/guide/learn/writing-tests-with-ai.md +0 -127
  198. package/public/vendor/vitest-docs/guide/learn/writing-tests.md +0 -231
  199. package/public/vendor/vitest-docs/guide/lifecycle.md +0 -379
  200. package/public/vendor/vitest-docs/guide/migration.md +0 -863
  201. package/public/vendor/vitest-docs/guide/mocking/classes.md +0 -158
  202. package/public/vendor/vitest-docs/guide/mocking/dates.md +0 -52
  203. package/public/vendor/vitest-docs/guide/mocking/file-system.md +0 -74
  204. package/public/vendor/vitest-docs/guide/mocking/functions.md +0 -61
  205. package/public/vendor/vitest-docs/guide/mocking/globals.md +0 -20
  206. package/public/vendor/vitest-docs/guide/mocking/modules.md +0 -414
  207. package/public/vendor/vitest-docs/guide/mocking/requests.md +0 -114
  208. package/public/vendor/vitest-docs/guide/mocking/timers.md +0 -48
  209. package/public/vendor/vitest-docs/guide/mocking.md +0 -239
  210. package/public/vendor/vitest-docs/guide/open-telemetry.md +0 -156
  211. package/public/vendor/vitest-docs/guide/parallelism.md +0 -82
  212. package/public/vendor/vitest-docs/guide/profiling-test-performance.md +0 -243
  213. package/public/vendor/vitest-docs/guide/projects.md +0 -291
  214. package/public/vendor/vitest-docs/guide/recipes.md +0 -59
  215. package/public/vendor/vitest-docs/guide/reporters.md +0 -723
  216. package/public/vendor/vitest-docs/guide/snapshot.md +0 -620
  217. package/public/vendor/vitest-docs/guide/test-annotations.md +0 -103
  218. package/public/vendor/vitest-docs/guide/test-context.md +0 -902
  219. package/public/vendor/vitest-docs/guide/test-tags.md +0 -314
  220. package/public/vendor/vitest-docs/guide/testing-types.md +0 -149
  221. package/public/vendor/vitest-docs/guide/ui.md +0 -160
  222. package/public/vendor/vitest-docs/guide/using-plugins.md +0 -5
  223. package/public/vendor/vitest-docs/manifest.json +0 -1691
  224. package/resources/index.js +0 -166
  225. package/resources/indexes.js +0 -77
  226. package/resources/manifest-schema.js +0 -46
  227. package/resources/paths.js +0 -20
  228. package/resources/patterns.js +0 -22
  229. package/resources/upstream-docs.js +0 -22
@@ -1,863 +0,0 @@
1
- # Migration Guide
2
-
3
- [Migrating to Vitest 3.0](https://v3.vitest.dev/guide/migration) | [Migrating to Vitest 2.0](https://v2.vitest.dev/guide/migration)
4
-
5
- ## Migrating to Vitest 4.0 {#vitest-4}
6
-
7
- ::: warning Prerequisites
8
- Vitest 4.0 requires **Vite >= 6.0.0** and **Node.js >= 20.0.0**. Before proceeding
9
- with any other migration steps, ensure your environment meets these requirements.
10
- Running Vitest 4.0 on older versions of Vite or Node.js is not supported and may
11
- result in unexpected errors.
12
- :::
13
-
14
- ### V8 Code Coverage Major Changes
15
-
16
- Vitest's V8 code coverage provider is now using more accurate coverage result remapping logic.
17
- It is expected for users to see changes in their coverage reports when updating from Vitest v3.
18
-
19
- In the past Vitest used [`v8-to-istanbul`](https://github.com/istanbuljs/v8-to-istanbul) for remapping V8 coverage results into your source files.
20
- This method wasn't very accurate and provided plenty of false positives in the coverage reports.
21
- We've now developed a new package that utilizes AST based analysis for the V8 coverage.
22
- This allows V8 reports to be as accurate as `@vitest/coverage-istanbul` reports.
23
-
24
- - Coverage ignore hints have updated. See [Coverage | Ignoring Code](/guide/coverage.html#ignoring-code).
25
- - `coverage.ignoreEmptyLines` is removed. Lines without runtime code are no longer included in reports.
26
- - `coverage.experimentalAstAwareRemapping` is removed. This option is now enabled by default, and is the only supported remapping method.
27
- - `coverage.ignoreClassMethods` is now supported by V8 provider too.
28
-
29
- ### Removed Options `coverage.all` and `coverage.extensions`
30
-
31
- In previous versions Vitest included all uncovered files in coverage report by default.
32
- This was due to `coverage.all` defaulting to `true`, and `coverage.include` defaulting to `**`.
33
- These default values were chosen for a good reason - it is impossible for testing tools to guess where users are storing their source files.
34
-
35
- This ended up having Vitest's coverage providers processing unexpected files, like minified Javascript, leading to slow/stuck coverage report generations.
36
- In Vitest v4 we have removed `coverage.all` completely and <ins>**defaulted to include only covered files in the report**</ins>.
37
-
38
- When upgrading to v4 it is recommended to define `coverage.include` in your configuration, and then start applying simple `coverage.exclude` patterns if needed.
39
-
40
- ```ts [vitest.config.ts]
41
- export default defineConfig({
42
- test: {
43
- coverage: {
44
- // Include covered and uncovered files matching this pattern:
45
- include: ['packages/**/src/**.{js,jsx,ts,tsx}'], // [!code ++]
46
-
47
- // Exclusion is applied for the files that match include pattern above
48
- // No need to define root level *.config.ts files or node_modules, as we didn't add those in include
49
- exclude: ['**/some-pattern/**'], // [!code ++]
50
-
51
- // These options are removed now
52
- all: true, // [!code --]
53
- extensions: ['js', 'ts'], // [!code --]
54
- }
55
- }
56
- })
57
- ```
58
-
59
- If `coverage.include` is not defined, coverage report will include only files that were loaded during test run:
60
- ```ts [vitest.config.ts]
61
- export default defineConfig({
62
- test: {
63
- coverage: {
64
- // Include not set, include only files that are loaded during test run
65
- include: undefined, // [!code ++]
66
-
67
- // Loaded files that match this pattern will be excluded:
68
- exclude: ['**/some-pattern/**'], // [!code ++]
69
- }
70
- }
71
- })
72
- ```
73
-
74
- See also new guides:
75
- - [Including and excluding files from coverage report](/guide/coverage.html#including-and-excluding-files-from-coverage-report) for examples
76
- - [Profiling Test Performance | Code coverage](/guide/profiling-test-performance.html#code-coverage) for tips about debugging coverage generation
77
-
78
- ### Simplified `exclude`
79
-
80
- By default, Vitest now only excludes tests from `node_modules` and `.git` folders. This means that Vitest no longer excludes:
81
-
82
- - `dist` and `cypress` folders
83
- - `.idea`, `.cache`, `.output`, `.temp` folders
84
- - config files like `rollup.config.js`, `prettier.config.js`, `ava.config.js` and so on
85
-
86
- If you need to limit the directory where your tests files are located, use the [`test.dir`](/config/dir) option instead because it is more performant than excluding files:
87
-
88
- ```ts
89
- import { configDefaults, defineConfig } from 'vitest/config'
90
-
91
- export default defineConfig({
92
- test: {
93
- dir: './frontend/tests', // [!code ++]
94
- },
95
- })
96
- ```
97
-
98
- To restore the previous behaviour, specify old `excludes` manually:
99
-
100
- ```ts
101
- import { configDefaults, defineConfig } from 'vitest/config'
102
-
103
- export default defineConfig({
104
- test: {
105
- exclude: [
106
- ...configDefaults.exclude,
107
- '**/dist/**', // [!code ++]
108
- '**/cypress/**', // [!code ++]
109
- '**/.{idea,git,cache,output,temp}/**', // [!code ++]
110
- '**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build,eslint,prettier}.config.*' // [!code ++]
111
- ],
112
- },
113
- })
114
- ```
115
-
116
- ### `spyOn` and `fn` Support Constructors
117
-
118
- Previously, if you tried to spy on a constructor with `vi.spyOn`, you would get an error like `Constructor <name> requires 'new'`. Since Vitest 4, all mocks called with a `new` keyword construct the instance instead of calling `mock.apply`. This means that the mock implementation has to use either the `function` or the `class` keyword in these cases:
119
-
120
- ```ts {12-14,16-20}
121
- const cart = {
122
- Apples: class Apples {
123
- getApples() {
124
- return 42
125
- }
126
- }
127
- }
128
-
129
- const Spy = vi.spyOn(cart, 'Apples')
130
- .mockImplementation(() => ({ getApples: () => 0 })) // [!code --]
131
- // with a function keyword
132
- .mockImplementation(function () {
133
- this.getApples = () => 0
134
- })
135
- // with a custom class
136
- .mockImplementation(class MockApples {
137
- getApples() {
138
- return 0
139
- }
140
- })
141
-
142
- const mock = new Spy()
143
- ```
144
-
145
- Note that now 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.
146
-
147
- ### Changes to Mocking
148
-
149
- Alongside new features like supporting constructors, Vitest 4 creates mocks differently to address several module mocking issues that we received over the years. This release attempts to make module spies less confusing, especially when working with classes.
150
-
151
- - `vi.fn().getMockName()` now returns `vi.fn()` by default instead of `spy`. This can affect snapshots with mocks - the name will be changed from `[MockFunction spy]` to `[MockFunction]`. Spies created with `vi.spyOn` will keep using the original name by default for better debugging experience
152
- - `vi.restoreAllMocks` no longer resets the state of spies and only restores spies created manually with `vi.spyOn`, automocks are no longer affected by this function (this also affects the config option [`restoreMocks`](/config/restoremocks)). Note that `.mockRestore` will still reset the mock implementation and clear the state
153
- - Calling `vi.spyOn` on a mock now returns the same mock
154
- - `mock.settledResults` are now populated immediately on function invocation with an `'incomplete'` result. When the promise is finished, the type is changed according to the result.
155
- - Automocked instance methods are now properly isolated, but share a state with the prototype. Overriding the prototype implementation will always affect instance methods unless the methods have a custom mock implementation of their own. Calling `.mockReset` on the mock also no longer breaks that inheritance.
156
- ```ts
157
- import { AutoMockedClass } from './example.js'
158
- const instance1 = new AutoMockedClass()
159
- const instance2 = new AutoMockedClass()
160
-
161
- instance1.method.mockReturnValue(42)
162
-
163
- expect(instance1.method()).toBe(42)
164
- expect(instance2.method()).toBe(undefined)
165
-
166
- expect(AutoMockedClass.prototype.method).toHaveBeenCalledTimes(2)
167
-
168
- instance1.method.mockReset()
169
- AutoMockedClass.prototype.method.mockReturnValue(100)
170
-
171
- expect(instance1.method()).toBe(100)
172
- expect(instance2.method()).toBe(100)
173
-
174
- expect(AutoMockedClass.prototype.method).toHaveBeenCalledTimes(4)
175
- ```
176
- - Automocked methods can no longer be restored, even with a manual `.mockRestore`. Automocked modules with `spy: true` will keep working as before
177
- - Automocked getters no longer call the original getter. By default, automocked getters now return `undefined`. You can keep using `vi.spyOn(object, name, 'get')` to spy on a getter and change its implementation
178
- - The mock `vi.fn(implementation).mockReset()` now correctly returns the mock implementation in `.getMockImplementation()`
179
- - `vi.fn().mock.invocationCallOrder` now starts with `1`, like Jest does, instead of `0`
180
-
181
- ### Standalone Mode with Filename Filter
182
-
183
- To improve user experience, Vitest will now start running the matched files when [`--standalone`](/guide/cli#standalone) is used with filename filter.
184
-
185
- ```sh
186
- # In Vitest v3 and below this command would ignore "math.test.ts" filename filter.
187
- # In Vitest v4 the math.test.ts will run automatically.
188
- $ vitest --standalone math.test.ts
189
- ```
190
-
191
- This allows users to create re-usable `package.json` scripts for standalone mode.
192
-
193
- ::: code-group
194
- ```json [package.json]
195
- {
196
- "scripts": {
197
- "test:dev": "vitest --standalone"
198
- }
199
- }
200
- ```
201
- ```bash [CLI]
202
- # Start Vitest in standalone mode, without running any files on start
203
- $ pnpm run test:dev
204
-
205
- # Run math.test.ts immediately
206
- $ pnpm run test:dev math.test.ts
207
- ```
208
- :::
209
-
210
- ### Replacing `vite-node` with [Module Runner](https://vite.dev/guide/api-environment-runtimes.html#modulerunner)
211
-
212
- Module Runner is a successor to `vite-node` implemented directly in Vite. Vitest now uses it directly instead of having a wrapper around Vite SSR handler. This means that certain features are no longer available:
213
-
214
- - `VITE_NODE_DEPS_MODULE_DIRECTORIES` environment variable was replaced with `VITEST_MODULE_DIRECTORIES`
215
- - Vitest no longer injects `__vitest_executor` into every [test runner](/api/advanced/runner). Instead, it injects `moduleRunner` which is an instance of [`ModuleRunner`](https://vite.dev/guide/api-environment-runtimes.html#modulerunner)
216
- - `vitest/execute` entry point was removed. It was always meant to be internal
217
- - [Custom environments](/guide/environment) no longer need to provide a `transformMode` property. Instead, provide `viteEnvironment`. If it is not provided, Vitest will use the environment name to transform files on the server (see [`server.environments`](https://vite.dev/guide/api-environment-instances.html))
218
- - `vite-node` is no longer a dependency of Vitest
219
- - `deps.optimizer.web` was renamed to [`deps.optimizer.client`](/config/deps#deps-client). You can also use any custom names to apply optimizer configs when using other server environments
220
-
221
- Vite has its own externalization mechanism, but we decided to keep using the old one to reduce the amount of breaking changes. You can keep using [`server.deps`](/config/server#deps) to inline or externalize packages.
222
-
223
- This update should not be noticeable unless you rely on advanced features mentioned above.
224
-
225
- ### `workspace` is Replaced with `projects`
226
-
227
- The `workspace` configuration option was renamed to [`projects`](/guide/projects) in Vitest 3.2. They are functionally the same, except you cannot specify another file as the source of your workspace (previously you could specify a file that would export an array of projects). Migrating to `projects` is easy, just move the code from `vitest.workspace.js` to `vitest.config.ts`:
228
-
229
- ::: code-group
230
- ```ts [vitest.config.js]
231
- import { defineConfig } from 'vitest/config'
232
-
233
- export default defineConfig({
234
- test: {
235
- workspace: './vitest.workspace.js', // [!code --]
236
- projects: [ // [!code ++]
237
- './packages/*', // [!code ++]
238
- { // [!code ++]
239
- test: { // [!code ++]
240
- name: 'unit', // [!code ++]
241
- }, // [!code ++]
242
- }, // [!code ++]
243
- ] // [!code ++]
244
- }
245
- })
246
- ```
247
- ```ts [vitest.workspace.js]
248
- import { defineWorkspace } from 'vitest/config' // [!code --]
249
-
250
- export default defineWorkspace([ // [!code --]
251
- './packages/*', // [!code --]
252
- { // [!code --]
253
- test: { // [!code --]
254
- name: 'unit', // [!code --]
255
- }, // [!code --]
256
- } // [!code --]
257
- ]) // [!code --]
258
- ```
259
- :::
260
-
261
- ### Browser Provider Rework
262
-
263
- In Vitest 4.0, the browser provider now accepts an object instead of a string (`'playwright'`, `'webdriverio'`). The `preview` is no longer a default. This makes it simpler to work with custom options and doesn't require adding `/// <reference` comments anymore.
264
-
265
- ```ts
266
- import { playwright } from '@vitest/browser-playwright' // [!code ++]
267
-
268
- export default defineConfig({
269
- test: {
270
- browser: {
271
- provider: 'playwright', // [!code --]
272
- provider: playwright({ // [!code ++]
273
- launchOptions: { // [!code ++]
274
- slowMo: 100, // [!code ++]
275
- }, // [!code ++]
276
- }), // [!code ++]
277
- instances: [
278
- {
279
- browser: 'chromium',
280
- launch: { // [!code --]
281
- slowMo: 100, // [!code --]
282
- }, // [!code --]
283
- },
284
- ],
285
- },
286
- },
287
- })
288
- ```
289
-
290
- The naming of properties in `playwright` factory now also aligns with [Playwright documentation](https://playwright.dev/docs/api/class-testoptions#test-options-launch-options) making it easier to find.
291
-
292
- With this change, the `@vitest/browser` package is no longer needed, and you can remove it from your dependencies. To support the context import, you should update the `@vitest/browser/context` to `vitest/browser`:
293
-
294
- ```ts
295
- import { page } from '@vitest/browser/context' // [!code --]
296
- import { page } from 'vitest/browser' // [!code ++]
297
-
298
- test('example', async () => {
299
- await page.getByRole('button').click()
300
- })
301
- ```
302
-
303
- The modules are identical, so doing a simple "Find and Replace" should be sufficient.
304
-
305
- If you were using the `@vitest/browser/utils` module, you can now import those utilities from `vitest/browser` as well:
306
-
307
- ```ts
308
- import { getElementError } from '@vitest/browser/utils' // [!code --]
309
- import { utils } from 'vitest/browser' // [!code ++]
310
- const { getElementError } = utils // [!code ++]
311
- ```
312
-
313
- ::: warning
314
- Both `@vitest/browser/context` and `@vitest/browser/utils` work at runtime during the transition period, but they will be removed in a future release.
315
- :::
316
-
317
- ### Pool Rework
318
-
319
- Vitest has used [`tinypool`](https://github.com/tinylibs/tinypool) for orchestrating how test files are run in the test runner workers. Tinypool has controlled how complex tasks like parallelism, isolation and IPC communication works internally. However we've found that Tinypool has some flaws that are slowing down development of Vitest. In Vitest v4 we've completely removed Tinypool and rewritten how pools work without new dependencies. Read more about reasoning from [feat!: rewrite pools without tinypool #8705
320
- ](https://github.com/vitest-dev/vitest/pull/8705).
321
-
322
- New pool architecture allows Vitest to simplify many previously complex configuration options:
323
-
324
- - `maxThreads` and `maxForks` are now `maxWorkers`.
325
- - Environment variables `VITEST_MAX_THREADS` and `VITEST_MAX_FORKS` are now `VITEST_MAX_WORKERS`.
326
- - `singleThread` and `singleFork` are now `maxWorkers: 1, isolate: false`. If your tests were relying on module reset between tests, you'll need to add [setupFile](/config/setupfiles) that calls [`vi.resetModules()`](/api/vi.html#vi-resetmodules) in [`beforeAll` test hook](/api/hooks#beforeall).
327
- - `poolOptions` is removed. All previous `poolOptions` are now top-level options. The `memoryLimit` of VM pools is renamed to `vmMemoryLimit`.
328
- - `threads.useAtomics` is removed. If you have a use case for this, feel free to open a new feature request.
329
- - Custom pool interface has been rewritten, see [Custom Pool](/guide/advanced/pool#custom-pool)
330
-
331
- ```ts
332
- export default defineConfig({
333
- test: {
334
- poolOptions: { // [!code --]
335
- forks: { // [!code --]
336
- execArgv: ['--expose-gc'], // [!code --]
337
- isolate: false, // [!code --]
338
- singleFork: true, // [!code --]
339
- }, // [!code --]
340
- vmThreads: { // [!code --]
341
- memoryLimit: '300Mb' // [!code --]
342
- }, // [!code --]
343
- }, // [!code --]
344
- execArgv: ['--expose-gc'], // [!code ++]
345
- isolate: false, // [!code ++]
346
- maxWorkers: 1, // [!code ++]
347
- vmMemoryLimit: '300Mb', // [!code ++]
348
- }
349
- })
350
- ```
351
-
352
- Previously it was not possible to specify some pool related options per project when using [Vitest Projects](/guide/projects). With the new architecture this is no longer a blocker.
353
-
354
- ::: code-group
355
- ```ts [Isolation per project]
356
- import { defineConfig } from 'vitest/config'
357
-
358
- export default defineConfig({
359
- test: {
360
- projects: [
361
- {
362
- // Non-isolated unit tests
363
- name: 'Unit tests',
364
- isolate: false,
365
- exclude: ['**.integration.test.ts'],
366
- },
367
- {
368
- // Isolated integration tests
369
- name: 'Integration tests',
370
- include: ['**.integration.test.ts'],
371
- },
372
- ],
373
- },
374
- })
375
- ```
376
- ```ts [Parallel & Sequential projects]
377
- import { defineConfig } from 'vitest/config'
378
-
379
- export default defineConfig({
380
- test: {
381
- projects: [
382
- {
383
- name: 'Parallel',
384
- exclude: ['**.sequential.test.ts'],
385
- },
386
- {
387
- name: 'Sequential',
388
- include: ['**.sequential.test.ts'],
389
- fileParallelism: false,
390
- },
391
- ],
392
- },
393
- })
394
- ```
395
- ```ts [Node CLI options per project]
396
- import { defineConfig } from 'vitest/config'
397
-
398
- export default defineConfig({
399
- test: {
400
- projects: [
401
- {
402
- name: 'Production env',
403
- execArgv: ['--env-file=.env.prod']
404
- },
405
- {
406
- name: 'Staging env',
407
- execArgv: ['--env-file=.env.staging']
408
- },
409
- ],
410
- },
411
- })
412
- ```
413
- :::
414
-
415
- See [Recipes](/guide/recipes) for more examples.
416
-
417
- ### Reporter Updates
418
-
419
- Reporter APIs `onCollected`, `onSpecsCollected`, `onPathsCollected`, `onTaskUpdate` and `onFinished` were removed. See [`Reporters API`](/api/advanced/reporters) for new alternatives. The new APIs were introduced in Vitest `v3.0.0`.
420
-
421
- The `basic` reporter was removed as it is equal to:
422
-
423
- ```ts
424
- export default defineConfig({
425
- test: {
426
- reporters: [
427
- ['default', { summary: false }]
428
- ]
429
- }
430
- })
431
- ```
432
-
433
- The [`verbose`](/guide/reporters#verbose-reporter) reporter now prints test cases as a flat list. To revert to the previous behaviour, use `--reporter=tree`:
434
-
435
- ```ts
436
- export default defineConfig({
437
- test: {
438
- reporters: ['verbose'], // [!code --]
439
- reporters: ['tree'], // [!code ++]
440
- }
441
- })
442
- ```
443
-
444
- ### Snapshots using Custom Elements Print the Shadow Root
445
-
446
- In Vitest 4.0 snapshots that include custom elements will print the shadow root contents. To restore the previous behavior, set the [`printShadowRoot` option](/config/snapshotformat) to `false`.
447
-
448
- ```js{15-22}
449
- // before Vitest 4.0
450
- exports[`custom element with shadow root 1`] = `
451
- "<body>
452
- <div>
453
- <custom-element />
454
- </div>
455
- </body>"
456
- `
457
-
458
- // after Vitest 4.0
459
- exports[`custom element with shadow root 1`] = `
460
- "<body>
461
- <div>
462
- <custom-element>
463
- #shadow-root
464
- <span
465
- class="some-name"
466
- data-test-id="33"
467
- id="5"
468
- >
469
- hello
470
- </span>
471
- </custom-element>
472
- </div>
473
- </body>"
474
- `
475
- ```
476
-
477
- ### Deprecated APIs are Removed
478
-
479
- Vitest 4.0 removes some deprecated APIs, including:
480
-
481
- - `poolMatchGlobs` config option. Use [`projects`](/guide/projects) instead.
482
- - `environmentMatchGlobs` config option. Use [`projects`](/guide/projects) instead.
483
- - `deps.external`, `deps.inline`, `deps.fallbackCJS` config options. Use `server.deps.external`, `server.deps.inline`, or `server.deps.fallbackCJS` instead.
484
- - `browser.testerScripts` config option. Use [`browser.testerHtmlPath`](/config/browser/testerhtmlpath) instead.
485
- - `minWorkers` config option. Only `maxWorkers` has any effect on how tests are running, so we are removing this public option.
486
- - Vitest no longer supports providing test options object as a third argument to `test` and `describe`. Use the second argument instead:
487
-
488
- ```ts
489
- test('example', () => { /* ... */ }, { retry: 2 }) // [!code --]
490
- test('example', { retry: 2 }, () => { /* ... */ }) // [!code ++]
491
- ```
492
-
493
- Note that providing a timeout number as the last argument is still supported:
494
-
495
- ```ts
496
- test('example', () => { /* ... */ }, 1000) // ✅
497
- ```
498
-
499
- This release also removes all deprecated types. This finally fixes an issue where Vitest accidentally pulled in `@types/node` (see [#5481](https://github.com/vitest-dev/vitest/issues/5481) and [#6141](https://github.com/vitest-dev/vitest/issues/6141)).
500
-
501
- ## Migrating from Jest {#jest}
502
-
503
- Vitest has been designed with a Jest compatible API, in order to make the migration from Jest as simple as possible. Despite those efforts, you may still run into the following differences:
504
-
505
- ### Globals as a Default
506
-
507
- Jest has their [globals API](https://jestjs.io/docs/api) enabled by default. Vitest does not. You can either enable globals via [the `globals` configuration setting](/config/globals) or update your code to use imports from the `vitest` module instead.
508
-
509
- If you decide to keep globals disabled, be aware that common libraries like [`testing-library`](https://testing-library.com/) will not run auto DOM [cleanup](https://testing-library.com/docs/svelte-testing-library/api/#cleanup).
510
-
511
- ### `mock.mockReset`
512
-
513
- Jest's [`mockReset`](https://jestjs.io/docs/mock-function-api#mockfnmockreset) replaces the mock implementation with an
514
- empty function that returns `undefined`.
515
-
516
- Vitest's [`mockReset`](/api/mock#mockreset) resets the mock implementation to its original.
517
- That is, resetting a mock created by `vi.fn(impl)` will reset the mock implementation to `impl`.
518
-
519
- ### `mock.mock` is Persistent
520
-
521
- Jest will recreate the mock state when `.mockClear` is called, meaning you always need to access it as a getter. Vitest, on the other hand, holds a persistent reference to the state, meaning you can reuse it:
522
-
523
- ```ts
524
- const mock = vi.fn()
525
- const state = mock.mock
526
- mock.mockClear()
527
-
528
- expect(state).toBe(mock.mock) // fails in Jest
529
- ```
530
-
531
- ### Module Mocks
532
-
533
- When mocking a module in Jest, the factory argument's return value is the default export. In Vitest, the factory argument has to return an object with each export explicitly defined. For example, the following `jest.mock` would have to be updated as follows:
534
-
535
- ```ts
536
- jest.mock('./some-path', () => 'hello') // [!code --]
537
- vi.mock('./some-path', () => ({ // [!code ++]
538
- default: 'hello', // [!code ++]
539
- })) // [!code ++]
540
- ```
541
-
542
- For more details please refer to the [`vi.mock` api section](/api/vi#vi-mock).
543
-
544
- ### Auto-Mocking Behaviour
545
-
546
- Unlike Jest, mocked modules in `<root>/__mocks__` are not loaded unless `vi.mock()` is called. If you need them to be mocked in every test, like in Jest, you can mock them inside [`setupFiles`](/config/setupfiles).
547
-
548
- ### Importing the Original of a Mocked Package
549
-
550
- If you are only partially mocking a package, you might have previously used Jest's function `requireActual`. In Vitest, you should replace these calls with `vi.importActual`.
551
-
552
- ```ts
553
- const { cloneDeep } = jest.requireActual('lodash/cloneDeep') // [!code --]
554
- const { cloneDeep } = await vi.importActual('lodash/cloneDeep') // [!code ++]
555
- ```
556
-
557
- ### Extends mocking to external libraries
558
-
559
- Where Jest does it by default, when mocking a module and wanting this mocking to be extended to other external libraries that use the same module, you should explicitly tell which 3rd-party library you want to be mocked, so the external library would be part of your source code, by using [server.deps.inline](/config/server#inline).
560
-
561
- ```
562
- server.deps.inline: ["lib-name"]
563
- ```
564
-
565
- ### expect.getState().currentTestName
566
-
567
- Vitest's `test` names are joined with a `>` symbol to make it easier to distinguish tests from suites, while Jest uses an empty space (` `).
568
-
569
- ```diff
570
- - `${describeTitle} ${testTitle}`
571
- + `${describeTitle} > ${testTitle}`
572
- ```
573
-
574
- ### Envs
575
-
576
- Just like Jest, Vitest sets `NODE_ENV` to `test`, if it wasn't set before. Vitest also has a counterpart for `JEST_WORKER_ID` called `VITEST_POOL_ID` (always less than or equal to `maxWorkers`), so if you rely on it, don't forget to rename it. Vitest also exposes `VITEST_WORKER_ID` which is a unique ID of a running worker - this number is not affected by `maxWorkers`, and will increase with each created worker.
577
-
578
- ### Replace property
579
-
580
- If you want to modify the object, you will use [replaceProperty API](https://jestjs.io/docs/jest-object#jestreplacepropertyobject-propertykey-value) in Jest, you can use [`vi.stubEnv`](/api/vi#vi-stubenv) or [`vi.spyOn`](/api/vi#vi-spyon) to do the same also in Vitest.
581
-
582
- ### Done Callback
583
-
584
- Vitest does not support the callback style of declaring tests. You can rewrite them to use `async`/`await` functions, or use Promise to mimic the callback style.
585
-
586
- ```js
587
- it('should work', (done) => { // [!code --]
588
- it('should work', () => new Promise(done => { // [!code ++]
589
- // ...
590
- done()
591
- }) // [!code --]
592
- })) // [!code ++]
593
- ```
594
-
595
- ### Hooks
596
-
597
- `beforeAll`/`beforeEach` hooks may return [teardown function](/api/hooks#beforeach) in Vitest. Because of that you may need to rewrite your hooks declarations, if they return something other than `undefined` or `null`:
598
-
599
- ```ts
600
- beforeEach(() => setActivePinia(createTestingPinia())) // [!code --]
601
- beforeEach(() => { setActivePinia(createTestingPinia()) }) // [!code ++]
602
- ```
603
-
604
- In Jest hooks are called sequentially (one after another). By default, Vitest runs hooks in a stack. To use Jest's behavior, update [`sequence.hooks`](/config/sequence#sequence-hooks) option:
605
-
606
- ```ts
607
- export default defineConfig({
608
- test: {
609
- sequence: { // [!code ++]
610
- hooks: 'list', // [!code ++]
611
- } // [!code ++]
612
- }
613
- })
614
- ```
615
-
616
- ### Types
617
-
618
- Vitest doesn't have an equivalent to `jest` namespace, so you will need to import types directly from `vitest`:
619
-
620
- ```ts
621
- let fn: jest.Mock<(name: string) => number> // [!code --]
622
- import type { Mock } from 'vitest' // [!code ++]
623
- let fn: Mock<(name: string) => number> // [!code ++]
624
- ```
625
-
626
- ### Timers
627
-
628
- Vitest doesn't support Jest's legacy timers.
629
-
630
- ### Timeout
631
-
632
- If you used `jest.setTimeout`, you would need to migrate to `vi.setConfig`:
633
-
634
- ```ts
635
- jest.setTimeout(5_000) // [!code --]
636
- vi.setConfig({ testTimeout: 5_000 }) // [!code ++]
637
- ```
638
-
639
- ### Vue Snapshots
640
-
641
- This is not a Jest-specific feature, but if you previously were using Jest with vue-cli preset, you will need to install [`jest-serializer-vue`](https://github.com/eddyerburgh/jest-serializer-vue) package, and specify it in [`snapshotSerializers`](/config/snapshotserializers):
642
-
643
- ```js [vitest.config.js]
644
- import { defineConfig } from 'vitest/config'
645
-
646
- export default defineConfig({
647
- test: {
648
- snapshotSerializers: ['jest-serializer-vue']
649
- }
650
- })
651
- ```
652
-
653
- Otherwise your snapshots will have a lot of escaped `"` characters.
654
-
655
- ### Custom Snapshot Matchers <Badge type="warning">experimental</Badge> <Version>4.1.3</Version>
656
-
657
- Jest imports snapshot composables from `jest-snapshot`. In Vitest, use `Snapshots` from `vitest` instead:
658
-
659
- ```ts
660
- const { toMatchSnapshot } = require('jest-snapshot') // [!code --]
661
- import { Snapshots } from 'vitest' // [!code ++]
662
- const { toMatchSnapshot } = Snapshots // [!code ++]
663
-
664
- expect.extend({
665
- toMatchTrimmedSnapshot(received: string, length: number) {
666
- return toMatchSnapshot.call(this, received.slice(0, length))
667
- },
668
- })
669
- ```
670
-
671
- For inline snapshots, the same applies:
672
-
673
- ```ts
674
- const { toMatchInlineSnapshot } = require('jest-snapshot') // [!code --]
675
- import { Snapshots } from 'vitest' // [!code ++]
676
- const { toMatchInlineSnapshot } = Snapshots // [!code ++]
677
-
678
- expect.extend({
679
- toMatchTrimmedInlineSnapshot(received: string, inlineSnapshot?: string) {
680
- return toMatchInlineSnapshot.call(this, received.slice(0, 10), inlineSnapshot)
681
- },
682
- })
683
- ```
684
-
685
- See [Custom Snapshot Matchers](/guide/snapshot#custom-snapshot-matchers) for the full guide.
686
-
687
- ## Migrating from Mocha + Chai + Sinon {#mocha-chai-sinon}
688
-
689
- Vitest provides excellent support for migrating from Mocha+Chai+Sinon test suites. While Vitest uses a Jest-compatible API by default, it also provides Chai-style assertions for spy/mock testing, making migration easier.
690
-
691
- ### Test Structure
692
-
693
- Mocha and Vitest have similar test structures, but with some differences:
694
-
695
- ```ts
696
- // Mocha
697
- describe('suite', () => {
698
- before(() => { /* setup */ })
699
- after(() => { /* teardown */ })
700
- beforeEach(() => { /* setup */ })
701
- afterEach(() => { /* teardown */ })
702
-
703
- it('test', () => {
704
- // test code
705
- })
706
- })
707
-
708
- // Vitest - same structure works!
709
- import { afterAll, afterEach, beforeAll, beforeEach, describe, it } from 'vitest'
710
-
711
- describe('suite', () => {
712
- beforeAll(() => { /* setup */ })
713
- afterAll(() => { /* teardown */ })
714
- beforeEach(() => { /* setup */ })
715
- afterEach(() => { /* teardown */ })
716
-
717
- it('test', () => {
718
- // test code
719
- })
720
- })
721
- ```
722
-
723
- ### Assertions
724
-
725
- Vitest includes Chai assertions by default, so Chai assertions work without changes:
726
-
727
- ```ts
728
- // Both Mocha+Chai and Vitest
729
- import { expect } from 'vitest' // or 'chai' in Mocha
730
-
731
- expect(value).to.equal(42)
732
- expect(value).to.be.true
733
- expect(array).to.have.lengthOf(3)
734
- expect(obj).to.have.property('key')
735
- ```
736
-
737
- ### Spy/Mock Assertions
738
-
739
- Vitest provides **Chai-style assertions** for spies and mocks, allowing you to migrate from Sinon without rewriting assertions:
740
-
741
- ```ts
742
- // Before (Mocha + Chai + Sinon)
743
- const sinon = require('sinon')
744
- const chai = require('chai')
745
- const sinonChai = require('sinon-chai')
746
- chai.use(sinonChai)
747
-
748
- const spy = sinon.spy(obj, 'method')
749
- obj.method('arg1', 'arg2')
750
-
751
- expect(spy).to.have.been.called
752
- expect(spy).to.have.been.calledOnce
753
- expect(spy).to.have.been.calledWith('arg1', 'arg2')
754
-
755
- // After (Vitest) - same assertion syntax!
756
- import { expect, vi } from 'vitest'
757
-
758
- const spy = vi.spyOn(obj, 'method')
759
- obj.method('arg1', 'arg2')
760
-
761
- expect(spy).to.have.been.called
762
- expect(spy).to.have.been.calledOnce
763
- expect(spy).to.have.been.calledWith('arg1', 'arg2')
764
- ```
765
-
766
- #### Complete Chai-Style Assertion Support
767
-
768
- Vitest supports all common sinon-chai assertions:
769
-
770
- | Sinon-Chai | Vitest | Description |
771
- |------------|--------|-------------|
772
- | `spy.called` | `called` | Spy was called at least once |
773
- | `spy.calledOnce` | `calledOnce` | Spy was called exactly once |
774
- | `spy.calledTwice` | `calledTwice` | Spy was called exactly twice |
775
- | `spy.calledThrice` | `calledThrice` | Spy was called exactly three times |
776
- | `spy.callCount(n)` | `callCount(n)` | Spy was called n times |
777
- | `spy.calledWith(...)` | `calledWith(...)` | Spy was called with specific args |
778
- | `spy.calledOnceWith(...)` | `calledOnceWith(...)` | Spy was called once with specific args |
779
- | `spy.returned(value)` | `returned` | Spy returned specific value |
780
-
781
- See the [Chai-Style Spy Assertions](/api/expect#chai-style-spy-assertions) documentation for the complete list.
782
-
783
- ### Creating Spies and Mocks
784
-
785
- Replace Sinon's spy/stub/mock creation with Vitest's `vi` utilities:
786
-
787
- ```ts
788
- // Sinon
789
- const sinon = require('sinon')
790
- const spy = sinon.spy()
791
- const stub = sinon.stub(obj, 'method')
792
- const mock = sinon.mock(obj)
793
-
794
- // Vitest
795
- import { vi } from 'vitest'
796
- const spy = vi.fn()
797
- const stub = vi.spyOn(obj, 'method')
798
- // Vitest doesn't have "mocks" - use spies instead
799
- ```
800
-
801
- ### Stubbing Return Values
802
-
803
- ```ts
804
- // Sinon
805
- stub.returns(42)
806
- stub.onFirstCall().returns(1)
807
- stub.onSecondCall().returns(2)
808
-
809
- // Vitest
810
- stub.mockReturnValue(42)
811
- stub.mockReturnValueOnce(1)
812
- stub.mockReturnValueOnce(2)
813
- ```
814
-
815
- ### Stubbing Implementations
816
-
817
- ```ts
818
- // Sinon
819
- stub.callsFake(arg => arg * 2)
820
-
821
- // Vitest
822
- stub.mockImplementation(arg => arg * 2)
823
- ```
824
-
825
- ### Restoring Spies
826
-
827
- ```ts
828
- // Sinon
829
- spy.restore()
830
- sinon.restore() // restore all
831
-
832
- // Vitest
833
- spy.mockRestore()
834
- vi.restoreAllMocks() // restore all
835
- ```
836
-
837
- ### Timers
838
-
839
- Both Sinon and Vitest use `@sinonjs/fake-timers` internally:
840
-
841
- ```ts
842
- // Sinon
843
- const clock = sinon.useFakeTimers()
844
- clock.tick(1000)
845
- clock.restore()
846
-
847
- // Vitest
848
- import { vi } from 'vitest'
849
- vi.useFakeTimers()
850
- vi.advanceTimersByTime(1000)
851
- vi.useRealTimers()
852
- ```
853
-
854
- ### Key Differences
855
-
856
- 1. **Globals**: Mocha provides globals by default. In Vitest, either import from `vitest` or enable [`globals`](/config/globals) config
857
- 2. **Assertion style**: You can use both Chai-style (`expect(spy).to.have.been.called`) and Jest-style (`expect(spy).toHaveBeenCalled()`)
858
- 3. **Parallel execution**: Vitest runs tests in parallel by default, Mocha runs sequentially
859
-
860
- For more information, see:
861
- - [Chai-Style Spy Assertions](/api/expect#chai-style-spy-assertions)
862
- - [Mocking Guide](/guide/mocking)
863
- - [Vi API](/api/vi)