@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,277 +0,0 @@
1
- # Using Matchers
2
-
3
- Vitest uses `expect` with "matchers" to assert that values meet certain conditions. This page covers the matchers you'll use most often. For the complete list, see the [Expect API Reference](/api/expect).
4
-
5
- ## Common Matchers
6
-
7
- The simplest way to test a value is with exact equality. When you write `expect(2 + 2).toBe(4)`, the [`toBe`](/api/expect#tobe) matcher checks that the value is exactly `4` using [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
8
-
9
- ```js
10
- import { expect, test } from 'vitest'
11
-
12
- test('two plus two is four', () => {
13
- expect(2 + 2).toBe(4)
14
- })
15
- ```
16
-
17
- This works great for primitive values like numbers, strings, and booleans. But when you're comparing objects, `toBe` checks *identity* (whether they're the exact same object in memory), not whether they have the same shape. That's where [`toEqual`](/api/expect#toequal) comes in. It recursively compares every field of an object or element of an array, ignoring object identity:
18
-
19
- ```js
20
- test('object assignment', () => {
21
- const data = { one: 1 }
22
- data.two = 2
23
-
24
- expect(data).toEqual({ one: 1, two: 2 })
25
- })
26
- ```
27
-
28
- Here's an example that shows the difference more clearly. Two objects with the same content are `toEqual` but not `toBe`:
29
-
30
- ```js
31
- test('toBe vs toEqual', () => {
32
- const a = { name: 'Alice' }
33
- const b = { name: 'Alice' }
34
-
35
- // These are different objects in memory
36
- expect(a).not.toBe(b)
37
-
38
- // But they have the same structure
39
- expect(a).toEqual(b)
40
- })
41
- ```
42
-
43
- There's also [`toStrictEqual`](/api/expect#tostrictequal), which is stricter than `toEqual` in three ways: it checks `undefined` properties, distinguishes sparse arrays from `undefined` values, and verifies that objects have the same type (not just the same shape):
44
-
45
- ```js
46
- test('toEqual vs toStrictEqual', () => {
47
- // toEqual ignores undefined properties
48
- expect({ a: 1 }).toEqual({ a: 1, b: undefined })
49
-
50
- // toStrictEqual catches them
51
- expect({ a: 1 }).not.toStrictEqual({ a: 1, b: undefined })
52
-
53
- // toEqual doesn't check object types
54
- class User {
55
- constructor(name) {
56
- this.name = name
57
- }
58
- }
59
- expect(new User('Alice')).toEqual({ name: 'Alice' })
60
- expect(new User('Alice')).not.toStrictEqual({ name: 'Alice' })
61
- })
62
- ```
63
-
64
- ::: tip
65
- A good rule of thumb: use `toBe` for primitives (numbers, strings, booleans), `toEqual` for comparing structure, and `toStrictEqual` when you also care about types and explicit `undefined` values.
66
- :::
67
-
68
- You can also negate any matcher by inserting `.not` before it. This is useful when you want to verify that something is *not* the case:
69
-
70
- ```js
71
- test('adding positive numbers is not zero', () => {
72
- expect(1 + 2).not.toBe(0)
73
- })
74
- ```
75
-
76
- ## Truthiness
77
-
78
- In tests you sometimes need to distinguish between `undefined`, `null`, and `false`. Other times you don't care about the exact value and just want to know if something is truthy or falsy. Vitest provides matchers for both situations:
79
-
80
- - [`toBeNull`](/api/expect#tobenull) matches only `null`
81
- - [`toBeUndefined`](/api/expect#tobeundefined) matches only `undefined`
82
- - [`toBeDefined`](/api/expect#tobedefined) is the opposite of `toBeUndefined`. It passes for anything that isn't `undefined`
83
- - [`toBeTruthy`](/api/expect#tobetruthy) matches anything that an `if` statement would treat as true
84
- - [`toBeFalsy`](/api/expect#tobefalsy) matches anything that an `if` statement would treat as false
85
-
86
- You should pick the matcher that most precisely describes what you're checking. Using `toBeTruthy` when you really mean `toBeDefined` can hide bugs, because `0` and `""` are both defined but falsy.
87
-
88
- ```js
89
- test('null checks', () => {
90
- const n = null
91
-
92
- expect(n).toBeNull()
93
- expect(n).toBeDefined()
94
- expect(n).toBeFalsy()
95
- expect(n).not.toBeTruthy()
96
- expect(n).not.toBeUndefined()
97
- })
98
-
99
- test('zero', () => {
100
- const z = 0
101
-
102
- expect(z).toBeDefined() // passes: 0 is defined
103
- expect(z).toBeFalsy() // passes: 0 is falsy
104
- expect(z).not.toBeNull() // passes: 0 is not null
105
- })
106
- ```
107
-
108
- ## Numbers
109
-
110
- Most number comparisons are straightforward. Vitest provides the matchers you'd expect for greater-than, less-than, and equality checks:
111
-
112
- ```js
113
- test('number comparisons', () => {
114
- const value = 2 + 2
115
-
116
- expect(value).toBeGreaterThan(3)
117
- expect(value).toBeGreaterThanOrEqual(3.5)
118
- expect(value).toBeLessThan(5)
119
- expect(value).toBeLessThanOrEqual(4.5)
120
-
121
- // For exact equality, both toBe and toEqual work the same for numbers
122
- expect(value).toBe(4)
123
- expect(value).toEqual(4)
124
- })
125
- ```
126
-
127
- There is one common gotcha with floating point arithmetic. In JavaScript, `0.1 + 0.2` doesn't equal `0.3` exactly (it's `0.30000000000000004`). This means a `toBe(0.3)` check will fail. Use [`toBeCloseTo`](/api/expect#tobecloseto) instead, which compares numbers within a small rounding error:
128
-
129
- ```js
130
- test('adding floating point numbers', () => {
131
- const value = 0.1 + 0.2
132
-
133
- // This won't work because of floating point rounding
134
- // expect(value).toBe(0.3)
135
-
136
- // This works
137
- expect(value).toBeCloseTo(0.3)
138
- })
139
- ```
140
-
141
- ## Strings
142
-
143
- You can test strings against regular expressions with [`toMatch`](/api/expect#tomatch). This is especially handy when you care about a pattern rather than an exact value, like checking that an error message contains a certain word or that a URL matches a particular format:
144
-
145
- ```js
146
- test('there is no I in team', () => {
147
- expect('team').not.toMatch(/I/)
148
- })
149
-
150
- test('version string matches semver format', () => {
151
- expect('vitest@1.0.0').toMatch(/vitest@\d+\.\d+\.\d+/)
152
- })
153
- ```
154
-
155
- ## Arrays and Iterables
156
-
157
- [`toContain`](/api/expect#tocontain) checks that an array (or any iterable, like a `Set`) includes a particular item. It uses `===` for comparison, so it works well for primitives:
158
-
159
- ```js
160
- test('the shopping list has milk in it', () => {
161
- const shoppingList = ['milk', 'bread', 'eggs', 'butter']
162
-
163
- expect(shoppingList).toContain('milk')
164
- expect(new Set(shoppingList)).toContain('milk')
165
- })
166
- ```
167
-
168
- If you need to check that an array contains an object with a particular structure, use [`toContainEqual`](/api/expect#tocontainequal) instead. It works like `toEqual` but for individual items inside an array.
169
-
170
- ## Objects
171
-
172
- When testing objects, you often want to check only a few important fields without specifying every property. [`toMatchObject`](/api/expect#tomatchobject) lets you do exactly that. It verifies that the object contains at least the properties you specify, and ignores any additional ones:
173
-
174
- ```js
175
- test('user has expected fields', () => {
176
- const user = {
177
- id: 1,
178
- name: 'Alice',
179
- email: 'alice@example.com',
180
- createdAt: '2024-01-01'
181
- }
182
-
183
- // We only care about name and email here
184
- expect(user).toMatchObject({
185
- name: 'Alice',
186
- email: 'alice@example.com',
187
- })
188
- })
189
- ```
190
-
191
- For checking individual properties, especially nested ones, [`toHaveProperty`](/api/expect#tohaveproperty) is more readable. You pass a dot-separated path and optionally an expected value:
192
-
193
- ```js
194
- test('object has property', () => {
195
- const user = {
196
- name: 'Alice',
197
- address: { city: 'Paris', zip: '75001' }
198
- }
199
-
200
- expect(user).toHaveProperty('name')
201
- expect(user).toHaveProperty('name', 'Alice')
202
- expect(user).toHaveProperty('address.city', 'Paris')
203
- expect(user).toHaveProperty('address.zip')
204
- })
205
- ```
206
-
207
- ## Asymmetric Matchers
208
-
209
- Sometimes you don't know the exact value, but you know its type or shape. Asymmetric matchers let you describe what a value should *look like* without pinning down the exact content. They work inside any matcher that does deep comparison, like `toEqual` or `toMatchObject`:
210
-
211
- ```js
212
- test('user has the right shape', () => {
213
- const user = createUser('Alice')
214
-
215
- expect(user).toEqual({
216
- id: expect.any(Number),
217
- name: 'Alice',
218
- email: expect.stringContaining('@'),
219
- roles: expect.arrayContaining(['viewer']),
220
- })
221
- })
222
- ```
223
-
224
- The most common asymmetric matchers are:
225
-
226
- - [`expect.any(Constructor)`](/api/expect#expect-any) matches any value created with the given constructor (e.g., `Number`, `String`, `Array`)
227
- - [`expect.stringContaining(str)`](/api/expect#expect-stringcontaining) matches a string that includes the given substring
228
- - [`expect.stringMatching(regex)`](/api/expect#expect-stringmatching) matches a string against a regular expression
229
- - [`expect.arrayContaining(arr)`](/api/expect#expect-arraycontaining) matches an array that includes all items in the expected array (order doesn't matter, extra items are allowed)
230
- - [`expect.objectContaining(obj)`](/api/expect#expect-objectcontaining) matches an object that includes at least the specified properties
231
-
232
- ## Exceptions
233
-
234
- To verify that a function throws an error, use [`toThrow`](/api/expect#tothrow). You need to wrap the call in another function so that Vitest can catch the error instead of letting it crash the test:
235
-
236
- ```js
237
- function compileCode(code) {
238
- if (code === '') {
239
- throw new Error('Cannot compile empty string')
240
- }
241
- return code
242
- }
243
-
244
- test('compiling an empty string throws', () => {
245
- // Check that it throws at all
246
- expect(() => compileCode('')).toThrow()
247
-
248
- // Check the error message
249
- expect(() => compileCode('')).toThrow('Cannot compile empty string')
250
-
251
- // Check the message with a regex
252
- expect(() => compileCode('')).toThrow(/empty string/)
253
- })
254
- ```
255
-
256
- ::: tip
257
- The wrapping function `() => compileCode('')` is important. If you wrote `expect(compileCode('')).toThrow()`, the error would be thrown *before* `expect` gets a chance to catch it, and the test would fail with an unhandled error instead.
258
- :::
259
-
260
- ## Soft Assertions
261
-
262
- Normally, a failing assertion stops the test immediately. That's useful most of the time, but sometimes you want to check several independent things and see all the failures at once rather than fixing them one by one.
263
-
264
- [`expect.soft`](/api/expect#soft) does exactly that. It records the failure but lets the test keep running:
265
-
266
- ```js
267
- test('check multiple fields', () => {
268
- const user = { name: 'Alice', age: 30, role: 'admin' }
269
-
270
- expect.soft(user.name).toBe('Alice')
271
- expect.soft(user.age).toBe(25) // this fails but execution continues
272
- expect.soft(user.role).toBe('admin')
273
- // the test report will show that age didn't match
274
- })
275
- ```
276
-
277
- This is especially useful for validating the shape of an API response or a complex object where multiple fields might be wrong at the same time.
@@ -1,277 +0,0 @@
1
- # Mock Functions
2
-
3
- When writing tests, you often need to replace a real function or module with a controlled version. This is called **mocking**. There are several reasons you might want to do this: maybe the real function makes network requests that would slow down your tests, or maybe you need to simulate an error that's hard to trigger with real code. Mock functions let you control what a dependency returns, observe how it was called, and isolate the code under test from side effects.
4
-
5
- Vitest provides mocking utilities through the [`vi`](/api/vi) object.
6
-
7
- ## Creating Mock Functions
8
-
9
- The simplest way to create a mock is with [`vi.fn()`](/api/vi#vi-fn). This gives you a function that does nothing by default (returns `undefined`), but tracks every call made to it:
10
-
11
- ```js
12
- import { expect, test, vi } from 'vitest'
13
-
14
- test('mock function basics', () => {
15
- const getApples = vi.fn()
16
-
17
- // Call it
18
- getApples()
19
-
20
- // Check it was called
21
- expect(getApples).toHaveBeenCalled()
22
- expect(getApples).toHaveBeenCalledTimes(1)
23
-
24
- // By default, a mock returns undefined
25
- expect(getApples()).toBeUndefined()
26
- })
27
- ```
28
-
29
- ## Mock Return Values
30
-
31
- A mock that always returns `undefined` isn't very useful on its own. You'll usually want to control what it returns so you can test how your code reacts to different values:
32
-
33
- ```js
34
- import { expect, test, vi } from 'vitest'
35
-
36
- test('mock return values', () => {
37
- const getApples = vi.fn()
38
-
39
- // Always return this value
40
- getApples.mockReturnValue(10)
41
- expect(getApples()).toBe(10)
42
-
43
- // Return this value only once, then fall back to the default
44
- getApples.mockReturnValueOnce(20)
45
- expect(getApples()).toBe(20) // 20 (one-time)
46
- expect(getApples()).toBe(10) // back to default
47
- })
48
- ```
49
-
50
- If the function you're mocking is async, use [`mockResolvedValue`](/api/mock#mockresolvedvalue) and [`mockRejectedValue`](/api/mock#mockrejectedvalue) to control the promise outcome:
51
-
52
- ```js
53
- test('mock async return values', async () => {
54
- const fetchUser = vi.fn()
55
-
56
- fetchUser.mockResolvedValue({ name: 'Alice' })
57
- const user = await fetchUser()
58
- expect(user.name).toBe('Alice')
59
-
60
- fetchUser.mockRejectedValue(new Error('Not found'))
61
- await expect(fetchUser()).rejects.toThrow('Not found')
62
- })
63
- ```
64
-
65
- ## Mock Implementation
66
-
67
- Sometimes you need more than a fixed return value. You want the mock to actually do something with its arguments. [`mockImplementation`](/api/mock#mockimplementation) lets you provide a full replacement function:
68
-
69
- ```js
70
- import { expect, test, vi } from 'vitest'
71
-
72
- test('mock with custom implementation', () => {
73
- const add = vi.fn()
74
- add.mockImplementation((a, b) => a + b)
75
-
76
- expect(add(1, 2)).toBe(3)
77
- expect(add(10, 20)).toBe(30)
78
- })
79
- ```
80
-
81
- As a shorthand, you can pass the implementation directly to `vi.fn()`:
82
-
83
- ```js
84
- const add = vi.fn((a, b) => a + b)
85
- ```
86
-
87
- ## Inspecting Calls
88
-
89
- One of the most powerful things about mock functions is that they remember every call made to them. You can assert on how many times a function was called, what arguments it received, and what it returned:
90
-
91
- ```js
92
- import { expect, test, vi } from 'vitest'
93
-
94
- test('inspecting mock calls', () => {
95
- const greet = vi.fn()
96
-
97
- greet('Alice')
98
- greet('Bob', 'Charlie')
99
-
100
- // Number of calls
101
- expect(greet).toHaveBeenCalledTimes(2)
102
-
103
- // Check specific arguments
104
- expect(greet).toHaveBeenCalledWith('Alice')
105
- expect(greet).toHaveBeenCalledWith('Bob', 'Charlie')
106
-
107
- // Check the arguments of a specific call by position
108
- expect(greet).toHaveBeenNthCalledWith(1, 'Alice')
109
- expect(greet).toHaveBeenLastCalledWith('Bob', 'Charlie')
110
-
111
- // Access the raw call data
112
- expect(greet.mock.calls).toEqual([
113
- ['Alice'],
114
- ['Bob', 'Charlie'],
115
- ])
116
- })
117
- ```
118
-
119
- The `.mock` property gives you full access to the call history. In addition to `.mock.calls`, you can also inspect `.mock.results` to see what the mock returned (or threw) on each call:
120
-
121
- ```js
122
- const double = vi.fn(x => x * 2)
123
-
124
- double(5)
125
- double(10)
126
-
127
- expect(double.mock.results).toEqual([
128
- { type: 'return', value: 10 },
129
- { type: 'return', value: 20 },
130
- ])
131
- ```
132
-
133
- ::: warning
134
- `.mock.calls` stores references to the arguments, not copies. If you pass an object to a mock and then mutate it afterwards, the recorded call will reflect the mutated state, not the state at the time of the call:
135
-
136
- ```js
137
- const fn = vi.fn()
138
- const obj = { count: 1 }
139
-
140
- fn(obj)
141
- obj.count = 2
142
-
143
- // ❌ This fails! mock.calls[0][0].count is now 2, not 1
144
- expect(fn).toHaveBeenCalledWith({ count: 1 })
145
- ```
146
-
147
- If you need to assert on the original values, you can use `mockImplementation` to capture a clone at call time:
148
-
149
- ```js
150
- const calls = []
151
- const fn = vi.fn((obj) => {
152
- calls.push(structuredClone(obj))
153
- })
154
-
155
- const obj = { count: 1 }
156
- fn(obj)
157
- obj.count = 2
158
-
159
- expect(calls[0]).toEqual({ count: 1 }) // ✅ passes
160
- ```
161
-
162
- Alternatively, you can make your assertion before the mutation happens.
163
- :::
164
-
165
- ## Spying on Methods
166
-
167
- [`vi.spyOn`](/api/vi#vi-spyon) is different from `vi.fn()` in an important way. Instead of creating a brand new function, it wraps an *existing* method on an object. The original implementation still works by default, but you can observe every call and optionally override the behavior:
168
-
169
- ```js
170
- import { expect, test, vi } from 'vitest'
171
-
172
- const calculator = {
173
- add(a, b) {
174
- return a + b
175
- },
176
- }
177
-
178
- test('spy on a method', () => {
179
- const spy = vi.spyOn(calculator, 'add')
180
-
181
- // The original implementation still works
182
- expect(calculator.add(1, 2)).toBe(3)
183
-
184
- // But we can observe calls
185
- expect(spy).toHaveBeenCalledWith(1, 2)
186
- expect(spy).toHaveBeenCalledTimes(1)
187
- })
188
-
189
- test('spy can override implementation', () => {
190
- const spy = vi.spyOn(calculator, 'add')
191
- spy.mockReturnValue(42)
192
-
193
- expect(calculator.add(1, 2)).toBe(42)
194
- })
195
- ```
196
-
197
- This is particularly useful when you want to verify that your code calls a method correctly without replacing the method's behavior entirely.
198
-
199
- ## Resetting Mocks
200
-
201
- Mock functions accumulate state as tests run. They remember every call, every return value, and any custom implementation you've set. If you don't reset them between tests, this state can leak and cause confusing failures. Vitest provides three levels of cleanup:
202
-
203
- - **[`mockClear()`](/api/mock#mockclear)** clears the recorded call history and return values, but keeps any custom implementation you've set
204
- - **[`mockReset()`](/api/mock#mockreset)** does everything `mockClear` does, and also removes any custom implementation, returning the mock to its default state
205
- - **[`mockRestore()`](/api/mock#mockrestore)** is specifically for spies created with `vi.spyOn`. It restores the original object method, effectively undoing the spy. On `vi.fn()` mocks, it behaves the same as `mockReset`
206
-
207
- In practice, the easiest approach is to restore all mocks automatically after each test:
208
-
209
- ```js
210
- import { afterEach, expect, test, vi } from 'vitest'
211
-
212
- const calculator = {
213
- add: (a, b) => a + b,
214
- }
215
-
216
- afterEach(() => {
217
- vi.restoreAllMocks()
218
- })
219
-
220
- test('spy is restored after the test', () => {
221
- const spy = vi.spyOn(calculator, 'add').mockReturnValue(42)
222
- expect(calculator.add(1, 2)).toBe(42)
223
- // afterEach will restore calculator.add to the original implementation
224
- })
225
- ```
226
-
227
- Even better, you can configure this globally with the [`restoreMocks`](/config/restoremocks) option so you don't need the `afterEach` at all:
228
-
229
- ```js [vitest.config.js]
230
- import { defineConfig } from 'vitest/config'
231
-
232
- export default defineConfig({
233
- test: {
234
- restoreMocks: true,
235
- },
236
- })
237
- ```
238
-
239
- ## Mocking Modules
240
-
241
- Sometimes you need to replace an [entire module](/guide/mocking/modules) rather than a single function. For example, a database client or a logger that you don't want running during tests. [`vi.mock`](/api/vi#vi-mock) lets you replace a module's exports with mock implementations:
242
-
243
- ```js
244
- import { expect, test, vi } from 'vitest'
245
- import { getUser } from './db.js'
246
-
247
- vi.mock(import('./db.js'), () => ({
248
- getUser: vi.fn(),
249
- }))
250
-
251
- test('mock a module', () => {
252
- vi.mocked(getUser).mockReturnValue({ name: 'Alice' })
253
-
254
- const user = getUser(1)
255
- expect(user.name).toBe('Alice')
256
- expect(getUser).toHaveBeenCalledWith(1)
257
- })
258
- ```
259
-
260
- ::: warning
261
- [`vi.mock`](/api/vi#vi-mock) calls are hoisted to the top of the file. They run before any imports. This means the mocked version is in place by the time your test code runs.
262
- :::
263
-
264
- ::: warning
265
- Always pass `import('./db.js')` rather than a plain string `'./db.js'`. When you use `import()`, TypeScript can infer the module's types, so the factory function's return value is type-checked and `importOriginal` returns the correctly typed module. As a bonus, if you rename or move the file in your IDE, the import path will be updated automatically. If you use a string, you lose both the type safety and the automatic refactoring.
266
- :::
267
-
268
- Vitest has comprehensive guides for specific mocking scenarios:
269
-
270
- - [Mocking Functions](/guide/mocking/functions)
271
- - [Mocking Modules](/guide/mocking/modules)
272
- - [Mocking Timers](/guide/mocking/timers)
273
- - [Mocking Dates](/guide/mocking/dates)
274
- - [Mocking Globals](/guide/mocking/globals)
275
- - [Mocking Requests](/guide/mocking/requests)
276
- - [Mocking the File System](/guide/mocking/file-system)
277
- - [Mocking Classes](/guide/mocking/classes)