@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,2304 +0,0 @@
1
- # expect
2
-
3
- The following types are used in the type signatures below
4
-
5
- ```ts
6
- type Awaitable<T> = T | PromiseLike<T>
7
- ```
8
-
9
- `expect` is used to create assertions. In this context `assertions` are functions that can be called to assert a statement. Vitest provides `chai` assertions by default and also `Jest` compatible assertions built on top of `chai`. Since Vitest 4.1, for spy/mock testing, Vitest also provides Chai-style assertions (e.g., [`expect(spy).to.have.been.called()`](#called)) alongside Jest-style assertions (e.g., `expect(spy).toHaveBeenCalled()`). Unlike `Jest`, Vitest supports a message as the second argument - if the assertion fails, the error message will be equal to it.
10
-
11
- ```ts
12
- export interface ExpectStatic extends Chai.ExpectStatic, AsymmetricMatchersContaining {
13
- <T>(actual: T, message?: string): Assertion<T>
14
- extend: (expects: MatchersObject) => void
15
- anything: () => any
16
- any: (constructor: unknown) => any
17
- getState: () => MatcherState
18
- setState: (state: Partial<MatcherState>) => void
19
- not: AsymmetricMatchersContaining
20
- }
21
- ```
22
-
23
- For example, this code asserts that an `input` value is equal to `2`. If it's not, the assertion will throw an error, and the test will fail.
24
-
25
- ```ts twoslash
26
- import { expect } from 'vitest'
27
-
28
- const input = Math.sqrt(4)
29
-
30
- expect(input).to.equal(2) // chai API
31
- expect(input).toBe(2) // jest API
32
- ```
33
-
34
- Technically this example doesn't use [`test`](/api/test) function, so in the console you will see Node.js error instead of Vitest output. To learn more about `test`, please read [Test API Reference](/api/test).
35
-
36
- Also, `expect` can be used statically to access matcher functions, described later, and more.
37
-
38
- ::: warning
39
- `expect` has no effect on testing types, if the expression doesn't have a type error. If you want to use Vitest as [type checker](/guide/testing-types), use [`expectTypeOf`](/api/expect-typeof) or [`assertType`](/api/assert-type).
40
- :::
41
-
42
- ## assert
43
-
44
- - **Type:** `Chai.AssertStatic`
45
-
46
- Vitest reexports chai's [`assert` API](https://www.chaijs.com/api/assert/) as `expect.assert` for convenience. You can see the supported methods on the [Assert API page](/api/assert).
47
-
48
- This is especially useful if you need to narrow down the type, since `expect.to*` methods do not support that:
49
-
50
- ```ts
51
- interface Cat {
52
- __type: 'Cat'
53
- mew(): void
54
- }
55
- interface Dog {
56
- __type: 'Dog'
57
- bark(): void
58
- }
59
- type Animal = Cat | Dog
60
-
61
- const animal: Animal = { __type: 'Dog', bark: () => {} }
62
-
63
- expect.assert(animal.__type === 'Dog')
64
- // does not show a type error!
65
- expect(animal.bark()).toBeUndefined()
66
- ```
67
-
68
- ::: tip
69
- Note that `expect.assert` also supports other type-narrowing methods (like `assert.isDefined`, `assert.exists` and so on).
70
- :::
71
-
72
- ## soft
73
-
74
- - **Type:** `ExpectStatic & (actual: any) => Assertions`
75
-
76
- `expect.soft` functions similarly to `expect`, but instead of terminating the test execution upon a failed assertion, it continues running and marks the failure as a test failure. All errors encountered during the test will be displayed until the test is completed.
77
-
78
- ```ts
79
- import { expect, test } from 'vitest'
80
-
81
- test('expect.soft test', () => {
82
- expect.soft(1 + 1).toBe(3) // mark the test as fail and continue
83
- expect.soft(1 + 2).toBe(4) // mark the test as fail and continue
84
- })
85
- // reporter will report both errors at the end of the run
86
- ```
87
-
88
- It can also be used with `expect`. if `expect` assertion fails, the test will be terminated and all errors will be displayed.
89
-
90
- ```ts
91
- import { expect, test } from 'vitest'
92
-
93
- test('expect.soft test', () => {
94
- expect.soft(1 + 1).toBe(3) // mark the test as fail and continue
95
- expect(1 + 2).toBe(4) // failed and terminate the test, all previous errors will be output
96
- expect.soft(1 + 3).toBe(5) // do not run
97
- })
98
- ```
99
-
100
- ::: warning
101
- `expect.soft` can only be used inside the [`test`](/api/test) function.
102
- :::
103
-
104
- ## poll
105
-
106
- ```ts
107
- interface ExpectPoll extends ExpectStatic {
108
- (actual: () => T, options?: { interval?: number; timeout?: number; message?: string }): Promise<Assertions<T>>
109
- }
110
- ```
111
-
112
- `expect.poll` reruns the _assertion_ until it is succeeded. You can configure how many times Vitest should rerun the `expect.poll` callback by setting `interval` and `timeout` options.
113
-
114
- If an error is thrown inside the `expect.poll` callback, Vitest will retry again until the timeout runs out.
115
-
116
- ```ts
117
- import { expect, test } from 'vitest'
118
-
119
- test('element exists', async () => {
120
- asyncInjectElement()
121
-
122
- await expect.poll(() => document.querySelector('.element')).toBeTruthy()
123
- })
124
- ```
125
-
126
- ::: warning
127
- `expect.poll` makes every assertion asynchronous, so you need to await it. Since Vitest 3, if you forget to await it, the test will fail with a warning to do so.
128
-
129
- `expect.poll` doesn't work with several matchers:
130
-
131
- - Snapshot matchers are not supported because they will always succeed. If your condition is flaky, consider using [`vi.waitFor`](/api/vi#vi-waitfor) instead to resolve it first:
132
-
133
- ```ts
134
- import { expect, vi } from 'vitest'
135
-
136
- const flakyValue = await vi.waitFor(() => getFlakyValue())
137
- expect(flakyValue).toMatchSnapshot()
138
- ```
139
-
140
- - `.resolves` and `.rejects` are not supported. `expect.poll` already awaits the condition if it's asynchronous.
141
- - `toThrow` and its aliases are not supported because the `expect.poll` condition is always resolved before the matcher gets the value
142
- :::
143
-
144
- ## not
145
-
146
- Using `not` will negate the assertion. For example, this code asserts that an `input` value is not equal to `2`. If it's equal, the assertion will throw an error, and the test will fail.
147
-
148
- ```ts
149
- import { expect, test } from 'vitest'
150
-
151
- const input = Math.sqrt(16)
152
-
153
- expect(input).not.to.equal(2) // chai API
154
- expect(input).not.toBe(2) // jest API
155
- ```
156
-
157
- ## toBe
158
-
159
- - **Type:** `(value: any) => Awaitable<void>`
160
-
161
- `toBe` can be used to assert if primitives are equal or that objects share the same reference. It is equivalent of calling `expect(Object.is(3, 3)).toBe(true)`. If the objects are not the same, but you want to check if their structures are identical, you can use [`toEqual`](#toequal).
162
-
163
- For example, the code below checks if the trader has 13 apples.
164
-
165
- ```ts
166
- import { expect, test } from 'vitest'
167
-
168
- const stock = {
169
- type: 'apples',
170
- count: 13,
171
- }
172
-
173
- test('stock has 13 apples', () => {
174
- expect(stock.type).toBe('apples')
175
- expect(stock.count).toBe(13)
176
- })
177
-
178
- test('stocks are the same', () => {
179
- const refStock = stock // same reference
180
-
181
- expect(stock).toBe(refStock)
182
- })
183
- ```
184
-
185
- Try not to use `toBe` with floating-point numbers. Since JavaScript rounds them, `0.1 + 0.2` is not strictly `0.3`. To reliably assert floating-point numbers, use [`toBeCloseTo`](#tobecloseto) assertion.
186
-
187
- ## toBeCloseTo
188
-
189
- - **Type:** `(value: number, numDigits?: number) => Awaitable<void>`
190
-
191
- Use `toBeCloseTo` to compare floating-point numbers. The optional `numDigits` argument limits the number of digits to check _after_ the decimal point. The default for `numDigits` is 2. For example:
192
-
193
- ```ts
194
- import { expect, test } from 'vitest'
195
-
196
- test.fails('decimals are not equal in javascript', () => {
197
- expect(0.2 + 0.1).toBe(0.3) // 0.2 + 0.1 is 0.30000000000000004
198
- })
199
-
200
- test('decimals are rounded to 5 after the point', () => {
201
- // 0.2 + 0.1 is 0.30000 | "000000000004" removed
202
- expect(0.2 + 0.1).toBeCloseTo(0.3, 5)
203
- // nothing from 0.30000000000000004 is removed
204
- expect(0.2 + 0.1).not.toBeCloseTo(0.3, 50)
205
- })
206
- ```
207
-
208
- ## toBeDefined
209
-
210
- - **Type:** `() => Awaitable<void>`
211
-
212
- `toBeDefined` asserts that the value is not equal to `undefined`. Useful use case would be to check if function _returned_ anything.
213
-
214
- ```ts
215
- import { expect, test } from 'vitest'
216
-
217
- function getApples() {
218
- return 3
219
- }
220
-
221
- test('function returned something', () => {
222
- expect(getApples()).toBeDefined()
223
- })
224
- ```
225
-
226
- ## toBeUndefined
227
-
228
- - **Type:** `() => Awaitable<void>`
229
-
230
- Opposite of `toBeDefined`, `toBeUndefined` asserts that the value _is_ equal to `undefined`. Useful use case would be to check if function hasn't _returned_ anything.
231
-
232
- ```ts
233
- import { expect, test } from 'vitest'
234
-
235
- function getApplesFromStock(stock: string) {
236
- if (stock === 'Bill') {
237
- return 13
238
- }
239
- }
240
-
241
- test('mary doesn\'t have a stock', () => {
242
- expect(getApplesFromStock('Mary')).toBeUndefined()
243
- })
244
- ```
245
-
246
- ## toBeTruthy
247
-
248
- - **Type:** `() => Awaitable<void>`
249
-
250
- `toBeTruthy` asserts that the value is true when converted to boolean. Useful if you don't care for the value, but just want to know it can be converted to `true`.
251
-
252
- For example, having this code you don't care for the return value of `stocks.getInfo` - it maybe a complex object, a string, or anything else. The code will still work.
253
-
254
- ```ts
255
- import { Stocks } from './stocks.js'
256
-
257
- const stocks = new Stocks()
258
- stocks.sync('Bill')
259
- if (stocks.getInfo('Bill')) {
260
- stocks.sell('apples', 'Bill')
261
- }
262
- ```
263
-
264
- So if you want to test that `stocks.getInfo` will be truthy, you could write:
265
-
266
- ```ts
267
- import { expect, test } from 'vitest'
268
- import { Stocks } from './stocks.js'
269
-
270
- const stocks = new Stocks()
271
-
272
- test('if we know Bill stock, sell apples to him', () => {
273
- stocks.sync('Bill')
274
- expect(stocks.getInfo('Bill')).toBeTruthy()
275
- })
276
- ```
277
-
278
- Everything in JavaScript is truthy, except `false`, `null`, `undefined`, `NaN`, `0`, `-0`, `0n`, `""` and `document.all`.
279
-
280
- ## toBeFalsy
281
-
282
- - **Type:** `() => Awaitable<void>`
283
-
284
- `toBeFalsy` asserts that the value is false when converted to boolean. Useful if you don't care for the value, but just want to know if it can be converted to `false`.
285
-
286
- For example, having this code you don't care for the return value of `stocks.stockFailed` - it may return any falsy value, but the code will still work.
287
-
288
- ```ts
289
- import { Stocks } from './stocks.js'
290
-
291
- const stocks = new Stocks()
292
- stocks.sync('Bill')
293
- if (!stocks.stockFailed('Bill')) {
294
- stocks.sell('apples', 'Bill')
295
- }
296
- ```
297
-
298
- So if you want to test that `stocks.stockFailed` will be falsy, you could write:
299
-
300
- ```ts
301
- import { expect, test } from 'vitest'
302
- import { Stocks } from './stocks.js'
303
-
304
- const stocks = new Stocks()
305
-
306
- test('if Bill stock hasn\'t failed, sell apples to him', () => {
307
- stocks.syncStocks('Bill')
308
- expect(stocks.stockFailed('Bill')).toBeFalsy()
309
- })
310
- ```
311
-
312
- Everything in JavaScript is truthy, except `false`, `null`, `undefined`, `NaN`, `0`, `-0`, `0n`, `""` and `document.all`.
313
-
314
- ## toBeNull
315
-
316
- - **Type:** `() => Awaitable<void>`
317
-
318
- `toBeNull` simply asserts if something is `null`. Alias for `.toBe(null)`.
319
-
320
- ```ts
321
- import { expect, test } from 'vitest'
322
-
323
- function apples() {
324
- return null
325
- }
326
-
327
- test('we don\'t have apples', () => {
328
- expect(apples()).toBeNull()
329
- })
330
- ```
331
-
332
- ## toBeNullable
333
-
334
- - **Type:** `() => Awaitable<void>`
335
-
336
- `toBeNullable` simply asserts if something is nullable (`null` or `undefined`).
337
-
338
- ```ts
339
- import { expect, test } from 'vitest'
340
-
341
- function apples() {
342
- return null
343
- }
344
-
345
- function bananas() {
346
- return undefined
347
- }
348
-
349
- test('we don\'t have apples', () => {
350
- expect(apples()).toBeNullable()
351
- })
352
-
353
- test('we don\'t have bananas', () => {
354
- expect(bananas()).toBeNullable()
355
- })
356
- ```
357
-
358
- ## toBeNaN
359
-
360
- - **Type:** `() => Awaitable<void>`
361
-
362
- `toBeNaN` simply asserts if something is `NaN`. Alias for `.toBe(NaN)`.
363
-
364
- ```ts
365
- import { expect, test } from 'vitest'
366
-
367
- let i = 0
368
-
369
- function getApplesCount() {
370
- i++
371
- return i > 1 ? Number.NaN : i
372
- }
373
-
374
- test('getApplesCount has some unusual side effects...', () => {
375
- expect(getApplesCount()).not.toBeNaN()
376
- expect(getApplesCount()).toBeNaN()
377
- })
378
- ```
379
-
380
- ## toBeOneOf
381
-
382
- - **Type:** `(sample: Array<any> | Set<any>) => any`
383
-
384
- `toBeOneOf` asserts if a value matches any of the values in the provided array or set.
385
-
386
- ::: warning EXPERIMENTAL
387
- Providing a `Set` is an experimental feature and may change in a future release.
388
- :::
389
-
390
- ```ts
391
- import { expect, test } from 'vitest'
392
-
393
- test('fruit is one of the allowed values', () => {
394
- expect(fruit).toBeOneOf(['apple', 'banana', 'orange'])
395
- })
396
- ```
397
-
398
- The asymmetric matcher is particularly useful when testing optional properties that could be either `null` or `undefined`:
399
-
400
- ```ts
401
- test('optional properties can be null or undefined', () => {
402
- const user = {
403
- firstName: 'John',
404
- middleName: undefined,
405
- lastName: 'Doe'
406
- }
407
-
408
- expect(user).toEqual({
409
- firstName: expect.any(String),
410
- middleName: expect.toBeOneOf([expect.any(String), undefined]),
411
- lastName: expect.any(String),
412
- })
413
- })
414
- ```
415
-
416
- :::tip
417
- You can use `expect.not` with this matcher to ensure a value does NOT match any of the provided options.
418
- :::
419
-
420
- ## toBeTypeOf
421
-
422
- - **Type:** `(c: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined') => Awaitable<void>`
423
-
424
- `toBeTypeOf` asserts if an actual value is of type of received type.
425
-
426
- ```ts
427
- import { expect, test } from 'vitest'
428
-
429
- const actual = 'stock'
430
-
431
- test('stock is type of string', () => {
432
- expect(actual).toBeTypeOf('string')
433
- })
434
- ```
435
-
436
- :::warning
437
- `toBeTypeOf` uses the native `typeof` operator under the hood with all its quirks, most notably that the value `null` has type `object`.
438
-
439
- ```ts
440
- test('toBeTypeOf cannot check for null or array', () => {
441
- expect(null).toBeTypeOf('object')
442
- expect([]).toBeTypeOf('object')
443
- })
444
- ```
445
- :::
446
-
447
- ## toBeInstanceOf
448
-
449
- - **Type:** `(c: any) => Awaitable<void>`
450
-
451
- `toBeInstanceOf` asserts if an actual value is instance of received class.
452
-
453
- ```ts
454
- import { expect, test } from 'vitest'
455
- import { Stocks } from './stocks.js'
456
-
457
- const stocks = new Stocks()
458
-
459
- test('stocks are instance of Stocks', () => {
460
- expect(stocks).toBeInstanceOf(Stocks)
461
- })
462
- ```
463
-
464
- ## toBeGreaterThan
465
-
466
- - **Type:** `(n: number | bigint) => Awaitable<void>`
467
-
468
- `toBeGreaterThan` asserts if actual value is greater than received one. Equal values will fail the test.
469
-
470
- ```ts
471
- import { expect, test } from 'vitest'
472
- import { getApples } from './stocks.js'
473
-
474
- test('have more then 10 apples', () => {
475
- expect(getApples()).toBeGreaterThan(10)
476
- })
477
- ```
478
-
479
- ## toBeGreaterThanOrEqual
480
-
481
- - **Type:** `(n: number | bigint) => Awaitable<void>`
482
-
483
- `toBeGreaterThanOrEqual` asserts if actual value is greater than received one or equal to it.
484
-
485
- ```ts
486
- import { expect, test } from 'vitest'
487
- import { getApples } from './stocks.js'
488
-
489
- test('have 11 apples or more', () => {
490
- expect(getApples()).toBeGreaterThanOrEqual(11)
491
- })
492
- ```
493
-
494
- ## toBeLessThan
495
-
496
- - **Type:** `(n: number | bigint) => Awaitable<void>`
497
-
498
- `toBeLessThan` asserts if actual value is less than received one. Equal values will fail the test.
499
-
500
- ```ts
501
- import { expect, test } from 'vitest'
502
- import { getApples } from './stocks.js'
503
-
504
- test('have less then 20 apples', () => {
505
- expect(getApples()).toBeLessThan(20)
506
- })
507
- ```
508
-
509
- ## toBeLessThanOrEqual
510
-
511
- - **Type:** `(n: number | bigint) => Awaitable<void>`
512
-
513
- `toBeLessThanOrEqual` asserts if actual value is less than received one or equal to it.
514
-
515
- ```ts
516
- import { expect, test } from 'vitest'
517
- import { getApples } from './stocks.js'
518
-
519
- test('have 11 apples or less', () => {
520
- expect(getApples()).toBeLessThanOrEqual(11)
521
- })
522
- ```
523
-
524
- ## toEqual
525
-
526
- - **Type:** `(received: any) => Awaitable<void>`
527
-
528
- `toEqual` asserts if actual value is equal to received one or has the same structure, if it is an object (compares them recursively). You can see the difference between `toEqual` and [`toBe`](#tobe) in this example:
529
-
530
- ```ts
531
- import { expect, test } from 'vitest'
532
-
533
- const stockBill = {
534
- type: 'apples',
535
- count: 13,
536
- }
537
-
538
- const stockMary = {
539
- type: 'apples',
540
- count: 13,
541
- }
542
-
543
- test('stocks have the same properties', () => {
544
- expect(stockBill).toEqual(stockMary)
545
- })
546
-
547
- test('stocks are not the same', () => {
548
- expect(stockBill).not.toBe(stockMary)
549
- })
550
- ```
551
-
552
- :::warning
553
- For `Error` objects, non-enumerable properties such as `name`, `message`, `cause` and `AggregateError.errors` are also compared. For `Error.cause`, the comparison is done asymmetrically:
554
-
555
- ```ts
556
- // success
557
- expect(new Error('hi', { cause: 'x' })).toEqual(new Error('hi'))
558
-
559
- // fail
560
- expect(new Error('hi')).toEqual(new Error('hi', { cause: 'x' }))
561
- ```
562
-
563
- To test if something was thrown, use [`toThrow`](#tothrow) assertion.
564
- :::
565
-
566
- ## toStrictEqual
567
-
568
- - **Type:** `(received: any) => Awaitable<void>`
569
-
570
- `toStrictEqual` asserts if the actual value is equal to the received one or has the same structure if it is an object (compares them recursively), and of the same type.
571
-
572
- Differences from [`.toEqual`](#toequal):
573
-
574
- - Keys with `undefined` properties are checked. e.g. `{a: undefined, b: 2}` does not match `{b: 2}` when using `.toStrictEqual`.
575
- - Array sparseness is checked. e.g. `[, 1]` does not match `[undefined, 1]` when using `.toStrictEqual`.
576
- - Object types are checked to be equal. e.g. A class instance with fields `a` and `b` will not equal a literal object with fields `a` and `b`.
577
-
578
- ```ts
579
- import { expect, test } from 'vitest'
580
-
581
- class Stock {
582
- constructor(type) {
583
- this.type = type
584
- }
585
- }
586
-
587
- test('structurally the same, but semantically different', () => {
588
- expect(new Stock('apples')).toEqual({ type: 'apples' })
589
- expect(new Stock('apples')).not.toStrictEqual({ type: 'apples' })
590
- })
591
- ```
592
-
593
- ## toContain
594
-
595
- - **Type:** `(received: string) => Awaitable<void>`
596
-
597
- `toContain` asserts if the actual value is in an array. `toContain` can also check whether a string is a substring of another string. If you are running tests in a browser-like environment, this assertion can also check if class is contained in a `classList`, or an element is inside another one.
598
-
599
- ```ts
600
- import { expect, test } from 'vitest'
601
- import { getAllFruits } from './stocks.js'
602
-
603
- test('the fruit list contains orange', () => {
604
- expect(getAllFruits()).toContain('orange')
605
- })
606
-
607
- test('pineapple contains apple', () => {
608
- expect('pineapple').toContain('apple')
609
- })
610
-
611
- test('the element contains a class and is contained', () => {
612
- const element = document.querySelector('#el')
613
- // element has a class
614
- expect(element.classList).toContain('flex')
615
- // element is inside another one
616
- expect(document.querySelector('#wrapper')).toContain(element)
617
- })
618
- ```
619
-
620
- ## toContainEqual
621
-
622
- - **Type:** `(received: any) => Awaitable<void>`
623
-
624
- `toContainEqual` asserts if an item with a specific structure and values is contained in an array.
625
- It works like [`toEqual`](#toequal) inside for each element.
626
-
627
- ```ts
628
- import { expect, test } from 'vitest'
629
- import { getFruitStock } from './stocks.js'
630
-
631
- test('apple available', () => {
632
- expect(getFruitStock()).toContainEqual({ fruit: 'apple', count: 5 })
633
- })
634
- ```
635
-
636
- ## toHaveLength
637
-
638
- - **Type:** `(received: number) => Awaitable<void>`
639
-
640
- `toHaveLength` asserts if an object has a `.length` property and it is set to a certain numeric value.
641
-
642
- ```ts
643
- import { expect, test } from 'vitest'
644
-
645
- test('toHaveLength', () => {
646
- expect('abc').toHaveLength(3)
647
- expect([1, 2, 3]).toHaveLength(3)
648
-
649
- expect('').not.toHaveLength(3) // doesn't have .length of 3
650
- expect({ length: 3 }).toHaveLength(3)
651
- })
652
- ```
653
-
654
- ## toHaveProperty
655
-
656
- - **Type:** `(key: any, received?: any) => Awaitable<void>`
657
-
658
- `toHaveProperty` asserts if a property at provided reference `key` exists for an object.
659
-
660
- You can provide an optional value argument also known as deep equality, like the `toEqual` matcher to compare the received property value.
661
-
662
- ```ts
663
- import { expect, test } from 'vitest'
664
-
665
- const invoice = {
666
- 'isActive': true,
667
- 'P.O': '12345',
668
- 'customer': {
669
- first_name: 'John',
670
- last_name: 'Doe',
671
- location: 'China',
672
- },
673
- 'total_amount': 5000,
674
- 'items': [
675
- {
676
- type: 'apples',
677
- quantity: 10,
678
- },
679
- {
680
- type: 'oranges',
681
- quantity: 5,
682
- },
683
- ],
684
- }
685
-
686
- test('John Doe Invoice', () => {
687
- expect(invoice).toHaveProperty('isActive') // assert that the key exists
688
- expect(invoice).toHaveProperty('total_amount', 5000) // assert that the key exists and the value is equal
689
-
690
- expect(invoice).not.toHaveProperty('account') // assert that this key does not exist
691
-
692
- // Deep referencing using dot notation
693
- expect(invoice).toHaveProperty('customer.first_name')
694
- expect(invoice).toHaveProperty('customer.last_name', 'Doe')
695
- expect(invoice).not.toHaveProperty('customer.location', 'India')
696
-
697
- // Deep referencing using an array containing the key
698
- expect(invoice).toHaveProperty('items[0].type', 'apples')
699
- expect(invoice).toHaveProperty('items.0.type', 'apples') // dot notation also works
700
-
701
- // Deep referencing using an array containing the keyPath
702
- expect(invoice).toHaveProperty(['items', 0, 'type'], 'apples')
703
- expect(invoice).toHaveProperty(['items', '0', 'type'], 'apples') // string notation also works
704
-
705
- // Wrap your key in an array to avoid the key from being parsed as a deep reference
706
- expect(invoice).toHaveProperty(['P.O'], '12345')
707
-
708
- // Deep equality of object property
709
- expect(invoice).toHaveProperty('items[0]', { type: 'apples', quantity: 10 })
710
- })
711
- ```
712
-
713
- ## toMatch
714
-
715
- - **Type:** `(received: string | regexp) => Awaitable<void>`
716
-
717
- `toMatch` asserts if a string matches a regular expression or a string.
718
-
719
- ```ts
720
- import { expect, test } from 'vitest'
721
-
722
- test('top fruits', () => {
723
- expect('top fruits include apple, orange and grape').toMatch(/apple/)
724
- expect('applefruits').toMatch('fruit') // toMatch also accepts a string
725
- })
726
- ```
727
-
728
- ## toMatchObject
729
-
730
- - **Type:** `(received: object | array) => Awaitable<void>`
731
-
732
- `toMatchObject` asserts if an object matches a subset of the properties of an object.
733
-
734
- You can also pass an array of objects. This is useful if you want to check that two arrays match in their number and order of elements, as opposed to `arrayContaining`, which allows for extra elements in the received array.
735
-
736
- ```ts
737
- import { expect, test } from 'vitest'
738
-
739
- const johnInvoice = {
740
- isActive: true,
741
- customer: {
742
- first_name: 'John',
743
- last_name: 'Doe',
744
- location: 'China',
745
- },
746
- total_amount: 5000,
747
- items: [
748
- {
749
- type: 'apples',
750
- quantity: 10,
751
- },
752
- {
753
- type: 'oranges',
754
- quantity: 5,
755
- },
756
- ],
757
- }
758
-
759
- const johnDetails = {
760
- customer: {
761
- first_name: 'John',
762
- last_name: 'Doe',
763
- location: 'China',
764
- },
765
- }
766
-
767
- test('invoice has john personal details', () => {
768
- expect(johnInvoice).toMatchObject(johnDetails)
769
- })
770
-
771
- test('the number of elements must match exactly', () => {
772
- // Assert that an array of object matches
773
- expect([{ foo: 'bar' }, { baz: 1 }]).toMatchObject([
774
- { foo: 'bar' },
775
- { baz: 1 },
776
- ])
777
- })
778
- ```
779
-
780
- ## toThrow
781
-
782
- - **Type:** `(expected?: any) => Awaitable<void>`
783
-
784
- - **Alias:** `toThrowError` <Deprecated />
785
-
786
- `toThrow` asserts if a function throws an error when it is called.
787
-
788
- You can provide an optional argument to test that a specific error is thrown:
789
-
790
- - `RegExp`: error message matches the pattern
791
- - `string`: error message includes the substring
792
- - any other value: compare with thrown value using deep equality (similar to `toEqual`)
793
-
794
- :::tip
795
- You must wrap the code in a function, otherwise the error will not be caught, and test will fail.
796
-
797
- This does not apply for async calls as [rejects](#rejects) correctly unwraps the promise:
798
- ```ts
799
- test('expect rejects toThrow', async ({ expect }) => {
800
- const promise = Promise.reject(new Error('Test'))
801
- await expect(promise).rejects.toThrow()
802
- })
803
- ```
804
- :::
805
-
806
- For example, if we want to test that `getFruitStock('pineapples')` throws, we could write:
807
-
808
- ```ts
809
- import { expect, test } from 'vitest'
810
-
811
- function getFruitStock(type: string) {
812
- if (type === 'pineapples') {
813
- throw new Error('Pineapples are not in stock')
814
- }
815
-
816
- // Do some other stuff
817
- }
818
-
819
- test('throws on pineapples', () => {
820
- // Test that the error message says "stock" somewhere: these are equivalent
821
- expect(() => getFruitStock('pineapples')).toThrow(/stock/)
822
- expect(() => getFruitStock('pineapples')).toThrow('stock')
823
-
824
- // Test the exact error message
825
- expect(() => getFruitStock('pineapples')).toThrow(
826
- /^Pineapples are not in stock$/,
827
- )
828
-
829
- expect(() => getFruitStock('pineapples')).toThrow(
830
- new Error('Pineapples are not in stock'),
831
- )
832
- expect(() => getFruitStock('pineapples')).toThrow(expect.objectContaining({
833
- message: 'Pineapples are not in stock',
834
- }))
835
- })
836
- ```
837
-
838
- :::tip
839
- To test async functions, use in combination with [rejects](#rejects).
840
-
841
- ```js
842
- function getAsyncFruitStock() {
843
- return Promise.reject(new Error('empty'))
844
- }
845
-
846
- test('throws on pineapples', async () => {
847
- await expect(() => getAsyncFruitStock()).rejects.toThrow('empty')
848
- })
849
- ```
850
- :::
851
-
852
- :::tip
853
- You can also test non-Error values that are thrown:
854
-
855
- ```ts
856
- test('throws non-Error values', () => {
857
- expect(() => { throw 42 }).toThrow(42)
858
- expect(() => { throw { message: 'error' } }).toThrow({ message: 'error' })
859
- })
860
- ```
861
- :::
862
-
863
- :::warning Unhandled Rejections with Fake Timers
864
- When using fake timers, an async function that rejects _during_ a `vi.advanceTimersByTimeAsync` call will trigger an [unhandled rejection](https://nodejs.org/api/process.html#event-unhandledrejection) — even if you later assert it with `.rejects.toThrow()`. This happens because the error is thrown before the `expect` chain has a chance to catch it.
865
-
866
- ```ts
867
- async function foo() {
868
- await new Promise(resolve => setTimeout(resolve, 100))
869
- throw new Error('boom')
870
- }
871
-
872
- test('rejects', async () => {
873
- const result = foo()
874
-
875
- await vi.advanceTimersByTimeAsync(100)
876
-
877
- // The assertion passes, but the error was already "unhandled" during advanceTimersByTimeAsync
878
- await expect(result).rejects.toThrow()
879
- })
880
- ```
881
-
882
- To avoid this, prefer [`vi.setTimerTickMode('nextTimerAsync')`](/api/vi#vi-settimertickmode) so that timers tick automatically as promises settle, without needing a manual advance:
883
-
884
- ```ts
885
- beforeEach(() => {
886
- vi.useFakeTimers()
887
- vi.setTimerTickMode('nextTimerAsync')
888
- })
889
-
890
- test('rejects', async () => {
891
- // No advanceTimersByTimeAsync needed — the error is caught by rejects.toThrow()
892
- await expect(foo()).rejects.toThrow('boom')
893
- })
894
- ```
895
-
896
- Alternatively, set up the `.rejects.toThrow()` assertion _before_ advancing timers so the rejection is handled immediately:
897
-
898
- ```ts
899
- test('rejects', async () => {
900
- const result = foo()
901
- const assertion = expect(result).rejects.toThrow('boom')
902
-
903
- await vi.advanceTimersByTimeAsync(100)
904
- await assertion
905
- })
906
- ```
907
- :::
908
-
909
- ## toMatchSnapshot
910
-
911
- - **Type:** `<T>(shape?: Partial<T> | string, hint?: string) => void`
912
-
913
- This ensures that a value matches the most recent snapshot.
914
-
915
- You can provide an optional `hint` string argument that is appended to the test name. Although Vitest always appends a number at the end of a snapshot name, short descriptive hints might be more useful than numbers to differentiate multiple snapshots in a single it or test block. Vitest sorts snapshots by name in the corresponding `.snap` file.
916
-
917
- :::tip
918
- When a snapshot mismatches and causes the test to fail, if the mismatch is expected, you can press `u` key to update the snapshot once. Or you can pass `-u` or `--update` CLI options to make Vitest always update the tests.
919
- :::
920
-
921
- ```ts
922
- import { expect, test } from 'vitest'
923
-
924
- test('matches snapshot', () => {
925
- const data = { foo: new Set(['bar', 'snapshot']) }
926
- expect(data).toMatchSnapshot()
927
- })
928
- ```
929
-
930
- You can also provide a shape of an object, if you are testing just a shape of an object, and don't need it to be 100% compatible:
931
-
932
- ```ts
933
- import { expect, test } from 'vitest'
934
-
935
- test('matches snapshot', () => {
936
- const data = { foo: new Set(['bar', 'snapshot']) }
937
- expect(data).toMatchSnapshot({ foo: expect.any(Set) })
938
- })
939
- ```
940
-
941
- ## toMatchInlineSnapshot
942
-
943
- - **Type:** `<T>(shape?: Partial<T> | string, snapshot?: string, hint?: string) => void`
944
-
945
- This ensures that a value matches the most recent snapshot.
946
-
947
- Vitest adds and updates the inlineSnapshot string argument to the matcher in the test file (instead of an external `.snap` file).
948
-
949
- ```ts
950
- import { expect, test } from 'vitest'
951
-
952
- test('matches inline snapshot', () => {
953
- const data = { foo: new Set(['bar', 'snapshot']) }
954
- // Vitest will update following content when updating the snapshot
955
- expect(data).toMatchInlineSnapshot(`
956
- {
957
- "foo": Set {
958
- "bar",
959
- "snapshot",
960
- },
961
- }
962
- `)
963
- })
964
- ```
965
-
966
- You can also provide a shape of an object, if you are testing just a shape of an object, and don't need it to be 100% compatible:
967
-
968
- ```ts
969
- import { expect, test } from 'vitest'
970
-
971
- test('matches snapshot', () => {
972
- const data = { foo: new Set(['bar', 'snapshot']) }
973
- expect(data).toMatchInlineSnapshot(
974
- { foo: expect.any(Set) },
975
- `
976
- {
977
- "foo": Any<Set>,
978
- }
979
- `
980
- )
981
- })
982
- ```
983
-
984
- ## toMatchFileSnapshot {#tomatchfilesnapshot}
985
-
986
- - **Type:** `<T>(filepath: string, hint?: string) => Promise<void>`
987
-
988
- Compare or update the snapshot with the content of a file explicitly specified (instead of the `.snap` file).
989
-
990
- ```ts
991
- import { expect, it } from 'vitest'
992
-
993
- it('render basic', async () => {
994
- const result = renderHTML(h('div', { class: 'foo' }))
995
- await expect(result).toMatchFileSnapshot('./test/basic.output.html')
996
- })
997
- ```
998
-
999
- Note that since file system operation is async, you need to use `await` with `toMatchFileSnapshot()`. If `await` is not used, Vitest treats it like `expect.soft`, meaning the code after the statement will continue to run even if the snapshot mismatches. After the test finishes, Vitest will check the snapshot and fail if there is a mismatch.
1000
-
1001
- ## toThrowErrorMatchingSnapshot
1002
-
1003
- - **Type:** `(hint?: string) => void`
1004
-
1005
- The same as [`toMatchSnapshot`](#tomatchsnapshot), but expects the same value as [`toThrow`](#tothrow).
1006
-
1007
- ## toThrowErrorMatchingInlineSnapshot
1008
-
1009
- - **Type:** `(snapshot?: string, hint?: string) => void`
1010
-
1011
- The same as [`toMatchInlineSnapshot`](#tomatchinlinesnapshot), but expects the same value as [`toThrow`](#tothrow).
1012
-
1013
- ## toMatchAriaSnapshot <Version type="experimental">4.1.4</Version> <Experimental /> {#tomatcharisnapshot}
1014
-
1015
- - **Type:** `() => void`
1016
-
1017
- Captures the accessibility tree of a DOM element and generate a snapshot file or compares it against a stored snapshot. See the [ARIA Snapshots guide](/guide/browser/aria-snapshots) for more details.
1018
-
1019
- ```ts
1020
- import { expect, test } from 'vitest'
1021
-
1022
- test('navigation accessibility', () => {
1023
- document.body.innerHTML = `
1024
- <nav aria-label="Actions">
1025
- <button>Save</button>
1026
- <button>Cancel</button>
1027
- </nav>
1028
- `
1029
- expect(document.querySelector('nav')).toMatchAriaSnapshot()
1030
- })
1031
- ```
1032
-
1033
- ## toMatchAriaInlineSnapshot <Version type="experimental">4.1.4</Version> <Experimental /> {#tomatchariainlinesnapshot}
1034
-
1035
- - **Type:** `(snapshot?: string) => void`
1036
-
1037
- Same as [`toMatchAriaSnapshot`](#tomatcharisnapshot), but stores the snapshot inline in the test file. See the [ARIA Snapshots guide](/guide/browser/aria-snapshots) for more details.
1038
-
1039
- ```ts
1040
- import { expect, test } from 'vitest'
1041
-
1042
- test('user profile', () => {
1043
- expect(document.body).toMatchAriaInlineSnapshot(`
1044
- - heading "Dashboard" [level=1]
1045
- - button /User \\d+/: Profile
1046
- `)
1047
- })
1048
- ```
1049
-
1050
- ## toHaveBeenCalled
1051
-
1052
- - **Type:** `() => Awaitable<void>`
1053
-
1054
- This assertion is useful for testing that a function has been called. Requires a spy function to be passed to `expect`.
1055
-
1056
- ```ts
1057
- import { expect, test, vi } from 'vitest'
1058
-
1059
- const market = {
1060
- buy(subject: string, amount: number) {
1061
- // ...
1062
- },
1063
- }
1064
-
1065
- test('spy function', () => {
1066
- const buySpy = vi.spyOn(market, 'buy')
1067
-
1068
- expect(buySpy).not.toHaveBeenCalled()
1069
-
1070
- market.buy('apples', 10)
1071
-
1072
- expect(buySpy).toHaveBeenCalled()
1073
- })
1074
- ```
1075
-
1076
- ## toHaveBeenCalledTimes
1077
-
1078
- - **Type:** `(amount: number) => Awaitable<void>`
1079
-
1080
- This assertion checks if a function was called a certain amount of times. Requires a spy function to be passed to `expect`.
1081
-
1082
- ```ts
1083
- import { expect, test, vi } from 'vitest'
1084
-
1085
- const market = {
1086
- buy(subject: string, amount: number) {
1087
- // ...
1088
- },
1089
- }
1090
-
1091
- test('spy function called two times', () => {
1092
- const buySpy = vi.spyOn(market, 'buy')
1093
-
1094
- market.buy('apples', 10)
1095
- market.buy('apples', 20)
1096
-
1097
- expect(buySpy).toHaveBeenCalledTimes(2)
1098
- })
1099
- ```
1100
-
1101
- ## toHaveBeenCalledWith
1102
-
1103
- - **Type:** `(...args: any[]) => Awaitable<void>`
1104
-
1105
- This assertion checks if a function was called at least once with certain parameters. Requires a spy function to be passed to `expect`.
1106
-
1107
- ```ts
1108
- import { expect, test, vi } from 'vitest'
1109
-
1110
- const market = {
1111
- buy(subject: string, amount: number) {
1112
- // ...
1113
- },
1114
- }
1115
-
1116
- test('spy function', () => {
1117
- const buySpy = vi.spyOn(market, 'buy')
1118
-
1119
- market.buy('apples', 10)
1120
- market.buy('apples', 20)
1121
-
1122
- expect(buySpy).toHaveBeenCalledWith('apples', 10)
1123
- expect(buySpy).toHaveBeenCalledWith('apples', 20)
1124
- })
1125
- ```
1126
-
1127
- ## toHaveBeenCalledBefore
1128
-
1129
- - **Type:** `(mock: MockInstance, failIfNoFirstInvocation?: boolean) => Awaitable<void>`
1130
-
1131
- This assertion checks if a `Mock` was called before another `Mock`.
1132
-
1133
- ```ts
1134
- test('calls mock1 before mock2', () => {
1135
- const mock1 = vi.fn()
1136
- const mock2 = vi.fn()
1137
-
1138
- mock1()
1139
- mock2()
1140
- mock1()
1141
-
1142
- expect(mock1).toHaveBeenCalledBefore(mock2)
1143
- })
1144
- ```
1145
-
1146
- ## toHaveBeenCalledAfter
1147
-
1148
- - **Type:** `(mock: MockInstance, failIfNoFirstInvocation?: boolean) => Awaitable<void>`
1149
-
1150
- This assertion checks if a `Mock` was called after another `Mock`.
1151
-
1152
- ```ts
1153
- test('calls mock1 after mock2', () => {
1154
- const mock1 = vi.fn()
1155
- const mock2 = vi.fn()
1156
-
1157
- mock2()
1158
- mock1()
1159
- mock2()
1160
-
1161
- expect(mock1).toHaveBeenCalledAfter(mock2)
1162
- })
1163
- ```
1164
-
1165
- ## toHaveBeenCalledExactlyOnceWith
1166
-
1167
- - **Type:** `(...args: any[]) => Awaitable<void>`
1168
-
1169
- This assertion checks if a function was called exactly once and with certain parameters. Requires a spy function to be passed to `expect`.
1170
-
1171
- ```ts
1172
- import { expect, test, vi } from 'vitest'
1173
-
1174
- const market = {
1175
- buy(subject: string, amount: number) {
1176
- // ...
1177
- },
1178
- }
1179
-
1180
- test('spy function', () => {
1181
- const buySpy = vi.spyOn(market, 'buy')
1182
-
1183
- market.buy('apples', 10)
1184
-
1185
- expect(buySpy).toHaveBeenCalledExactlyOnceWith('apples', 10)
1186
- })
1187
- ```
1188
-
1189
- ## toHaveBeenLastCalledWith
1190
-
1191
- - **Type:** `(...args: any[]) => Awaitable<void>`
1192
-
1193
- This assertion checks if a function was called with certain parameters at its last invocation. Requires a spy function to be passed to `expect`.
1194
-
1195
- ```ts
1196
- import { expect, test, vi } from 'vitest'
1197
-
1198
- const market = {
1199
- buy(subject: string, amount: number) {
1200
- // ...
1201
- },
1202
- }
1203
-
1204
- test('spy function', () => {
1205
- const buySpy = vi.spyOn(market, 'buy')
1206
-
1207
- market.buy('apples', 10)
1208
- market.buy('apples', 20)
1209
-
1210
- expect(buySpy).not.toHaveBeenLastCalledWith('apples', 10)
1211
- expect(buySpy).toHaveBeenLastCalledWith('apples', 20)
1212
- })
1213
- ```
1214
-
1215
- ## toHaveBeenNthCalledWith
1216
-
1217
- - **Type:** `(time: number, ...args: any[]) => Awaitable<void>`
1218
-
1219
- This assertion checks if a function was called with certain parameters at the certain time. The count starts at 1. So, to check the second entry, you would write `.toHaveBeenNthCalledWith(2, ...)`.
1220
-
1221
- Requires a spy function to be passed to `expect`.
1222
-
1223
- ```ts
1224
- import { expect, test, vi } from 'vitest'
1225
-
1226
- const market = {
1227
- buy(subject: string, amount: number) {
1228
- // ...
1229
- },
1230
- }
1231
-
1232
- test('first call of spy function called with right params', () => {
1233
- const buySpy = vi.spyOn(market, 'buy')
1234
-
1235
- market.buy('apples', 10)
1236
- market.buy('apples', 20)
1237
-
1238
- expect(buySpy).toHaveBeenNthCalledWith(1, 'apples', 10)
1239
- })
1240
- ```
1241
-
1242
- ## toHaveReturned
1243
-
1244
- - **Type:** `() => Awaitable<void>`
1245
-
1246
- This assertion checks if a function has successfully returned a value at least once (i.e., did not throw an error). Requires a spy function to be passed to `expect`.
1247
-
1248
- ```ts
1249
- import { expect, test, vi } from 'vitest'
1250
-
1251
- function getApplesPrice(amount: number) {
1252
- const PRICE = 10
1253
- return amount * PRICE
1254
- }
1255
-
1256
- test('spy function returned a value', () => {
1257
- const getPriceSpy = vi.fn(getApplesPrice)
1258
-
1259
- const price = getPriceSpy(10)
1260
-
1261
- expect(price).toBe(100)
1262
- expect(getPriceSpy).toHaveReturned()
1263
- })
1264
- ```
1265
-
1266
- ## toHaveReturnedTimes
1267
-
1268
- - **Type:** `(amount: number) => Awaitable<void>`
1269
-
1270
- This assertion checks if a function has successfully returned a value an exact amount of times (i.e., did not throw an error). Requires a spy function to be passed to `expect`.
1271
-
1272
- ```ts
1273
- import { expect, test, vi } from 'vitest'
1274
-
1275
- test('spy function returns a value two times', () => {
1276
- const sell = vi.fn((product: string) => ({ product }))
1277
-
1278
- sell('apples')
1279
- sell('bananas')
1280
-
1281
- expect(sell).toHaveReturnedTimes(2)
1282
- })
1283
- ```
1284
-
1285
- ## toHaveReturnedWith
1286
-
1287
- - **Type:** `(returnValue: any) => Awaitable<void>`
1288
-
1289
- You can call this assertion to check if a function has successfully returned a value with certain parameters at least once. Requires a spy function to be passed to `expect`.
1290
-
1291
- ```ts
1292
- import { expect, test, vi } from 'vitest'
1293
-
1294
- test('spy function returns a product', () => {
1295
- const sell = vi.fn((product: string) => ({ product }))
1296
-
1297
- sell('apples')
1298
-
1299
- expect(sell).toHaveReturnedWith({ product: 'apples' })
1300
- })
1301
- ```
1302
-
1303
- ## toHaveLastReturnedWith
1304
-
1305
- - **Type:** `(returnValue: any) => Awaitable<void>`
1306
-
1307
- You can call this assertion to check if a function has successfully returned a certain value when it was last invoked. Requires a spy function to be passed to `expect`.
1308
-
1309
- ```ts
1310
- import { expect, test, vi } from 'vitest'
1311
-
1312
- test('spy function returns bananas on a last call', () => {
1313
- const sell = vi.fn((product: string) => ({ product }))
1314
-
1315
- sell('apples')
1316
- sell('bananas')
1317
-
1318
- expect(sell).toHaveLastReturnedWith({ product: 'bananas' })
1319
- })
1320
- ```
1321
-
1322
- ## toHaveNthReturnedWith
1323
-
1324
- - **Type:** `(time: number, returnValue: any) => Awaitable<void>`
1325
-
1326
- You can call this assertion to check if a function has successfully returned a value with certain parameters on a certain call. Requires a spy function to be passed to `expect`.
1327
-
1328
- The count starts at 1. So, to check the second entry, you would write `.toHaveNthReturnedWith(2, ...)`.
1329
-
1330
- ```ts
1331
- import { expect, test, vi } from 'vitest'
1332
-
1333
- test('spy function returns bananas on second call', () => {
1334
- const sell = vi.fn((product: string) => ({ product }))
1335
-
1336
- sell('apples')
1337
- sell('bananas')
1338
-
1339
- expect(sell).toHaveNthReturnedWith(2, { product: 'bananas' })
1340
- })
1341
- ```
1342
-
1343
- ## toHaveResolved
1344
-
1345
- - **Type:** `() => Awaitable<void>`
1346
-
1347
- This assertion checks if a function has successfully resolved a value at least once (i.e., did not reject). Requires a spy function to be passed to `expect`.
1348
-
1349
- If the function returned a promise, but it was not resolved yet, this will fail.
1350
-
1351
- ```ts
1352
- import { expect, test, vi } from 'vitest'
1353
- import db from './db/apples.js'
1354
-
1355
- async function getApplesPrice(amount: number) {
1356
- return amount * await db.get('price')
1357
- }
1358
-
1359
- test('spy function resolved a value', async () => {
1360
- const getPriceSpy = vi.fn(getApplesPrice)
1361
-
1362
- const price = await getPriceSpy(10)
1363
-
1364
- expect(price).toBe(100)
1365
- expect(getPriceSpy).toHaveResolved()
1366
- })
1367
- ```
1368
-
1369
- ## toHaveResolvedTimes
1370
-
1371
- - **Type:** `(amount: number) => Awaitable<void>`
1372
-
1373
- This assertion checks if a function has successfully resolved a value an exact amount of times (i.e., did not reject). Requires a spy function to be passed to `expect`.
1374
-
1375
- This will only count resolved promises. If the function returned a promise, but it was not resolved yet, it will not be counted.
1376
-
1377
- ```ts
1378
- import { expect, test, vi } from 'vitest'
1379
-
1380
- test('spy function resolved a value two times', async () => {
1381
- const sell = vi.fn((product: string) => Promise.resolve({ product }))
1382
-
1383
- await sell('apples')
1384
- await sell('bananas')
1385
-
1386
- expect(sell).toHaveResolvedTimes(2)
1387
- })
1388
- ```
1389
-
1390
- ## toHaveResolvedWith
1391
-
1392
- - **Type:** `(returnValue: any) => Awaitable<void>`
1393
-
1394
- You can call this assertion to check if a function has successfully resolved a certain value at least once. Requires a spy function to be passed to `expect`.
1395
-
1396
- If the function returned a promise, but it was not resolved yet, this will fail.
1397
-
1398
- ```ts
1399
- import { expect, test, vi } from 'vitest'
1400
-
1401
- test('spy function resolved a product', async () => {
1402
- const sell = vi.fn((product: string) => Promise.resolve({ product }))
1403
-
1404
- await sell('apples')
1405
-
1406
- expect(sell).toHaveResolvedWith({ product: 'apples' })
1407
- })
1408
- ```
1409
-
1410
- ## toHaveLastResolvedWith
1411
-
1412
- - **Type:** `(returnValue: any) => Awaitable<void>`
1413
-
1414
- You can call this assertion to check if a function has successfully resolved a certain value when it was last invoked. Requires a spy function to be passed to `expect`.
1415
-
1416
- If the function returned a promise, but it was not resolved yet, this will fail.
1417
-
1418
- ```ts
1419
- import { expect, test, vi } from 'vitest'
1420
-
1421
- test('spy function resolves bananas on a last call', async () => {
1422
- const sell = vi.fn((product: string) => Promise.resolve({ product }))
1423
-
1424
- await sell('apples')
1425
- await sell('bananas')
1426
-
1427
- expect(sell).toHaveLastResolvedWith({ product: 'bananas' })
1428
- })
1429
- ```
1430
-
1431
- ## toHaveNthResolvedWith
1432
-
1433
- - **Type:** `(time: number, returnValue: any) => Awaitable<void>`
1434
-
1435
- You can call this assertion to check if a function has successfully resolved a certain value on a specific invocation. Requires a spy function to be passed to `expect`.
1436
-
1437
- If the function returned a promise, but it was not resolved yet, this will fail.
1438
-
1439
- The count starts at 1. So, to check the second entry, you would write `.toHaveNthResolvedWith(2, ...)`.
1440
-
1441
- ```ts
1442
- import { expect, test, vi } from 'vitest'
1443
-
1444
- test('spy function returns bananas on second call', async () => {
1445
- const sell = vi.fn((product: string) => Promise.resolve({ product }))
1446
-
1447
- await sell('apples')
1448
- await sell('bananas')
1449
-
1450
- expect(sell).toHaveNthResolvedWith(2, { product: 'bananas' })
1451
- })
1452
- ```
1453
-
1454
- ## called <Version>4.1.0</Version> {#called}
1455
-
1456
- - **Type:** `Assertion` (property, not a method)
1457
-
1458
- Chai-style assertion that checks if a spy was called at least once. This is equivalent to `toHaveBeenCalled()`.
1459
-
1460
- ::: tip
1461
- This is a property assertion following sinon-chai conventions. Access it without parentheses: `expect(spy).to.have.been.called`
1462
- :::
1463
-
1464
- ```ts
1465
- import { expect, test, vi } from 'vitest'
1466
-
1467
- test('spy was called', () => {
1468
- const spy = vi.fn()
1469
-
1470
- spy()
1471
-
1472
- expect(spy).to.have.been.called
1473
- expect(spy).to.not.have.been.called // negation
1474
- })
1475
- ```
1476
-
1477
- ## callCount <Version>4.1.0</Version> {#callcount}
1478
-
1479
- - **Type:** `(count: number) => void`
1480
-
1481
- Chai-style assertion that checks if a spy was called a specific number of times. This is equivalent to `toHaveBeenCalledTimes(count)`.
1482
-
1483
- ```ts
1484
- import { expect, test, vi } from 'vitest'
1485
-
1486
- test('spy call count', () => {
1487
- const spy = vi.fn()
1488
-
1489
- spy()
1490
- spy()
1491
- spy()
1492
-
1493
- expect(spy).to.have.callCount(3)
1494
- })
1495
- ```
1496
-
1497
- ## calledWith <Version>4.1.0</Version> {#calledwith}
1498
-
1499
- - **Type:** `(...args: any[]) => void`
1500
-
1501
- Chai-style assertion that checks if a spy was called with specific arguments at least once. This is equivalent to `toHaveBeenCalledWith(...args)`.
1502
-
1503
- ```ts
1504
- import { expect, test, vi } from 'vitest'
1505
-
1506
- test('spy called with arguments', () => {
1507
- const spy = vi.fn()
1508
-
1509
- spy('apple', 10)
1510
- spy('banana', 20)
1511
-
1512
- expect(spy).to.have.been.calledWith('apple', 10)
1513
- expect(spy).to.have.been.calledWith('banana', 20)
1514
- })
1515
- ```
1516
-
1517
- ## calledOnce <Version>4.1.0</Version> {#calledonce}
1518
-
1519
- - **Type:** `Assertion` (property, not a method)
1520
-
1521
- Chai-style assertion that checks if a spy was called exactly once. This is equivalent to `toHaveBeenCalledOnce()`.
1522
-
1523
- ::: tip
1524
- This is a property assertion following sinon-chai conventions. Access it without parentheses: `expect(spy).to.have.been.calledOnce`
1525
- :::
1526
-
1527
- ```ts
1528
- import { expect, test, vi } from 'vitest'
1529
-
1530
- test('spy called once', () => {
1531
- const spy = vi.fn()
1532
-
1533
- spy()
1534
-
1535
- expect(spy).to.have.been.calledOnce
1536
- })
1537
- ```
1538
-
1539
- ## calledOnceWith <Version>4.1.0</Version> {#calledoncewith}
1540
-
1541
- - **Type:** `(...args: any[]) => void`
1542
-
1543
- Chai-style assertion that checks if a spy was called exactly once with specific arguments. This is equivalent to `toHaveBeenCalledExactlyOnceWith(...args)`.
1544
-
1545
- ```ts
1546
- import { expect, test, vi } from 'vitest'
1547
-
1548
- test('spy called once with arguments', () => {
1549
- const spy = vi.fn()
1550
-
1551
- spy('apple', 10)
1552
-
1553
- expect(spy).to.have.been.calledOnceWith('apple', 10)
1554
- })
1555
- ```
1556
-
1557
- ## calledTwice <Version>4.1.0</Version> {#calledtwice}
1558
-
1559
- - **Type:** `Assertion` (property, not a method)
1560
-
1561
- Chai-style assertion that checks if a spy was called exactly twice. This is equivalent to `toHaveBeenCalledTimes(2)`.
1562
-
1563
- ::: tip
1564
- This is a property assertion following sinon-chai conventions. Access it without parentheses: `expect(spy).to.have.been.calledTwice`
1565
- :::
1566
-
1567
- ```ts
1568
- import { expect, test, vi } from 'vitest'
1569
-
1570
- test('spy called twice', () => {
1571
- const spy = vi.fn()
1572
-
1573
- spy()
1574
- spy()
1575
-
1576
- expect(spy).to.have.been.calledTwice
1577
- })
1578
- ```
1579
-
1580
- ## calledThrice <Version>4.1.0</Version> {#calledthrice}
1581
-
1582
- - **Type:** `Assertion` (property, not a method)
1583
-
1584
- Chai-style assertion that checks if a spy was called exactly three times. This is equivalent to `toHaveBeenCalledTimes(3)`.
1585
-
1586
- ::: tip
1587
- This is a property assertion following sinon-chai conventions. Access it without parentheses: `expect(spy).to.have.been.calledThrice`
1588
- :::
1589
-
1590
- ```ts
1591
- import { expect, test, vi } from 'vitest'
1592
-
1593
- test('spy called thrice', () => {
1594
- const spy = vi.fn()
1595
-
1596
- spy()
1597
- spy()
1598
- spy()
1599
-
1600
- expect(spy).to.have.been.calledThrice
1601
- })
1602
- ```
1603
-
1604
- ## lastCalledWith
1605
-
1606
- - **Type:** `(...args: any[]) => void`
1607
-
1608
- Chai-style assertion that checks if the last call to a spy was made with specific arguments. This is equivalent to `toHaveBeenLastCalledWith(...args)`.
1609
-
1610
- ```ts
1611
- import { expect, test, vi } from 'vitest'
1612
-
1613
- test('spy last called with', () => {
1614
- const spy = vi.fn()
1615
-
1616
- spy('apple', 10)
1617
- spy('banana', 20)
1618
-
1619
- expect(spy).to.have.been.lastCalledWith('banana', 20)
1620
- })
1621
- ```
1622
-
1623
- ## nthCalledWith
1624
-
1625
- - **Type:** `(n: number, ...args: any[]) => void`
1626
-
1627
- Chai-style assertion that checks if the nth call to a spy was made with specific arguments. This is equivalent to `toHaveBeenNthCalledWith(n, ...args)`.
1628
-
1629
- ```ts
1630
- import { expect, test, vi } from 'vitest'
1631
-
1632
- test('spy nth called with', () => {
1633
- const spy = vi.fn()
1634
-
1635
- spy('apple', 10)
1636
- spy('banana', 20)
1637
- spy('cherry', 30)
1638
-
1639
- expect(spy).to.have.been.nthCalledWith(2, 'banana', 20)
1640
- })
1641
- ```
1642
-
1643
- ## returned <Version>4.1.0</Version> {#returned}
1644
-
1645
- - **Type:** `(value: any) => void`
1646
-
1647
- Chai-style assertion that checks if a spy returned a specific value at least once. This is equivalent to `toHaveReturnedWith(value)`.
1648
-
1649
- ```ts
1650
- import { expect, test, vi } from 'vitest'
1651
-
1652
- test('spy returned', () => {
1653
- const spy = vi.fn(() => 'value')
1654
-
1655
- spy()
1656
-
1657
- expect(spy).to.have.returned('value')
1658
- })
1659
- ```
1660
-
1661
- ## returnedWith <Version>4.1.0</Version> {#returnedwith}
1662
-
1663
- - **Type:** `(value: any) => void`
1664
-
1665
- Chai-style assertion that checks if a spy returned a specific value at least once. This is equivalent to `toHaveReturnedWith(value)`.
1666
-
1667
- ```ts
1668
- import { expect, test, vi } from 'vitest'
1669
-
1670
- test('spy returned with value', () => {
1671
- const spy = vi.fn()
1672
- .mockReturnValueOnce('apple')
1673
- .mockReturnValueOnce('banana')
1674
-
1675
- spy()
1676
- spy()
1677
-
1678
- expect(spy).to.have.returnedWith('apple')
1679
- expect(spy).to.have.returnedWith('banana')
1680
- })
1681
- ```
1682
-
1683
- ## returnedTimes <Version>4.1.0</Version> {#returnedtimes}
1684
-
1685
- - **Type:** `(count: number) => void`
1686
-
1687
- Chai-style assertion that checks if a spy returned successfully a specific number of times. This is equivalent to `toHaveReturnedTimes(count)`.
1688
-
1689
- ```ts
1690
- import { expect, test, vi } from 'vitest'
1691
-
1692
- test('spy returned times', () => {
1693
- const spy = vi.fn(() => 'result')
1694
-
1695
- spy()
1696
- spy()
1697
- spy()
1698
-
1699
- expect(spy).to.have.returnedTimes(3)
1700
- })
1701
- ```
1702
-
1703
- ## lastReturnedWith
1704
-
1705
- - **Type:** `(value: any) => void`
1706
-
1707
- Chai-style assertion that checks if the last return value of a spy matches the expected value. This is equivalent to `toHaveLastReturnedWith(value)`.
1708
-
1709
- ```ts
1710
- import { expect, test, vi } from 'vitest'
1711
-
1712
- test('spy last returned with', () => {
1713
- const spy = vi.fn()
1714
- .mockReturnValueOnce('apple')
1715
- .mockReturnValueOnce('banana')
1716
-
1717
- spy()
1718
- spy()
1719
-
1720
- expect(spy).to.have.lastReturnedWith('banana')
1721
- })
1722
- ```
1723
-
1724
- ## nthReturnedWith
1725
-
1726
- - **Type:** `(n: number, value: any) => void`
1727
-
1728
- Chai-style assertion that checks if the nth return value of a spy matches the expected value. This is equivalent to `toHaveNthReturnedWith(n, value)`.
1729
-
1730
- ```ts
1731
- import { expect, test, vi } from 'vitest'
1732
-
1733
- test('spy nth returned with', () => {
1734
- const spy = vi.fn()
1735
- .mockReturnValueOnce('apple')
1736
- .mockReturnValueOnce('banana')
1737
- .mockReturnValueOnce('cherry')
1738
-
1739
- spy()
1740
- spy()
1741
- spy()
1742
-
1743
- expect(spy).to.have.nthReturnedWith(2, 'banana')
1744
- })
1745
- ```
1746
-
1747
- ## calledBefore <Version>4.1.0</Version> {#calledbefore}
1748
-
1749
- - **Type:** `(mock: MockInstance, failIfNoFirstInvocation?: boolean) => void`
1750
-
1751
- Chai-style assertion that checks if a spy was called before another spy. This is equivalent to `toHaveBeenCalledBefore(mock, failIfNoFirstInvocation)`.
1752
-
1753
- ```ts
1754
- import { expect, test, vi } from 'vitest'
1755
-
1756
- test('spy called before another', () => {
1757
- const spy1 = vi.fn()
1758
- const spy2 = vi.fn()
1759
-
1760
- spy1()
1761
- spy2()
1762
-
1763
- expect(spy1).to.have.been.calledBefore(spy2)
1764
- })
1765
- ```
1766
-
1767
- ## calledAfter <Version>4.1.0</Version> {#calledafter}
1768
-
1769
- - **Type:** `(mock: MockInstance, failIfNoFirstInvocation?: boolean) => void`
1770
-
1771
- Chai-style assertion that checks if a spy was called after another spy. This is equivalent to `toHaveBeenCalledAfter(mock, failIfNoFirstInvocation)`.
1772
-
1773
- ```ts
1774
- import { expect, test, vi } from 'vitest'
1775
-
1776
- test('spy called after another', () => {
1777
- const spy1 = vi.fn()
1778
- const spy2 = vi.fn()
1779
-
1780
- spy1()
1781
- spy2()
1782
-
1783
- expect(spy2).to.have.been.calledAfter(spy1)
1784
- })
1785
- ```
1786
-
1787
- ::: tip Migration Guide
1788
- For a complete guide on migrating from Mocha+Chai+Sinon to Vitest, see the [Migration Guide](/guide/migration#mocha-chai-sinon).
1789
- :::
1790
-
1791
- ## toSatisfy
1792
-
1793
- - **Type:** `(predicate: (value: any) => boolean) => Awaitable<void>`
1794
-
1795
- This assertion checks if a value satisfies a certain predicate.
1796
-
1797
- ```ts
1798
- import { describe, expect, it } from 'vitest'
1799
-
1800
- const isOdd = (value: number) => value % 2 !== 0
1801
-
1802
- describe('toSatisfy()', () => {
1803
- it('pass with 0', () => {
1804
- expect(1).toSatisfy(isOdd)
1805
- })
1806
-
1807
- it('pass with negation', () => {
1808
- expect(2).not.toSatisfy(isOdd)
1809
- })
1810
- })
1811
- ```
1812
-
1813
- ## resolves
1814
-
1815
- - **Type:** `Promisify<Assertions>`
1816
-
1817
- `resolves` is intended to remove boilerplate when asserting asynchronous code. Use it to unwrap value from the pending promise and assert its value with usual assertions. If the promise rejects, the assertion will fail.
1818
-
1819
- It returns the same `Assertions` object, but all matchers now return `Promise`, so you would need to `await` it. Also works with `chai` assertions.
1820
-
1821
- For example, if you have a function, that makes an API call and returns some data, you may use this code to assert its return value:
1822
-
1823
- ```ts
1824
- import { expect, test } from 'vitest'
1825
-
1826
- async function buyApples() {
1827
- return fetch('/buy/apples').then(r => r.json())
1828
- }
1829
-
1830
- test('buyApples returns new stock id', async () => {
1831
- // toEqual returns a promise now, so you HAVE to await it
1832
- await expect(buyApples()).resolves.toEqual({ id: 1 }) // jest API
1833
- await expect(buyApples()).resolves.to.equal({ id: 1 }) // chai API
1834
- })
1835
- ```
1836
-
1837
- :::warning
1838
- If the assertion is not awaited, then you will have a false-positive test that will pass every time. To make sure that assertions are actually called, you may use [`expect.assertions(number)`](#expect-assertions).
1839
-
1840
- Since Vitest 3, if a method is not awaited, Vitest will show a warning at the end of the test. In Vitest 4, the test will be marked as "failed" if the assertion is not awaited.
1841
- :::
1842
-
1843
- ## rejects
1844
-
1845
- - **Type:** `Promisify<Assertions>`
1846
-
1847
- `rejects` is intended to remove boilerplate when asserting asynchronous code. Use it to unwrap reason why the promise was rejected, and assert its value with usual assertions. If the promise successfully resolves, the assertion will fail.
1848
-
1849
- It returns the same `Assertions` object, but all matchers now return `Promise`, so you would need to `await` it. Also works with `chai` assertions.
1850
-
1851
- For example, if you have a function that fails when you call it, you may use this code to assert the reason:
1852
-
1853
- ```ts
1854
- import { expect, test } from 'vitest'
1855
-
1856
- async function buyApples(id) {
1857
- if (!id) {
1858
- throw new Error('no id')
1859
- }
1860
- }
1861
-
1862
- test('buyApples throws an error when no id provided', async () => {
1863
- // toThrow returns a promise now, so you HAVE to await it
1864
- await expect(buyApples()).rejects.toThrow('no id')
1865
- })
1866
- ```
1867
-
1868
- :::warning
1869
- If the assertion is not awaited, then you will have a false-positive test that will pass every time. To make sure that assertions were actually called, you can use [`expect.assertions(number)`](#expect-assertions).
1870
-
1871
- Since Vitest 3, if a method is not awaited, Vitest will show a warning at the end of the test. In Vitest 4, the test will be marked as "failed" if the assertion is not awaited.
1872
- :::
1873
-
1874
- ## expect.assertions
1875
-
1876
- - **Type:** `(count: number) => void`
1877
-
1878
- After the test has passed or failed verify that a certain number of assertions was called during a test. A useful case would be to check if an asynchronous code was called.
1879
-
1880
- For example, if we have a function that asynchronously calls two matchers, we can assert that they were actually called.
1881
-
1882
- ```ts
1883
- import { expect, test } from 'vitest'
1884
-
1885
- async function doAsync(...cbs) {
1886
- await Promise.all(
1887
- cbs.map((cb, index) => cb({ index })),
1888
- )
1889
- }
1890
-
1891
- test('all assertions are called', async () => {
1892
- expect.assertions(2)
1893
- function callback1(data) {
1894
- expect(data).toBeTruthy()
1895
- }
1896
- function callback2(data) {
1897
- expect(data).toBeTruthy()
1898
- }
1899
-
1900
- await doAsync(callback1, callback2)
1901
- })
1902
- ```
1903
- ::: warning
1904
- When using `assertions` with async concurrent tests, `expect` from the local [Test Context](/guide/test-context) must be used to ensure the right test is detected.
1905
- :::
1906
-
1907
- ## expect.hasAssertions
1908
-
1909
- - **Type:** `() => void`
1910
-
1911
- After the test has passed or failed verify that at least one assertion was called during a test. A useful case would be to check if an asynchronous code was called.
1912
-
1913
- For example, if you have a code that calls a callback, we can make an assertion inside a callback, but the test will always pass if we don't check if an assertion was called.
1914
-
1915
- ```ts
1916
- import { expect, test } from 'vitest'
1917
- import { db } from './db.js'
1918
-
1919
- const cbs = []
1920
-
1921
- function onSelect(cb) {
1922
- cbs.push(cb)
1923
- }
1924
-
1925
- // after selecting from db, we call all callbacks
1926
- function select(id) {
1927
- return db.select({ id }).then((data) => {
1928
- return Promise.all(
1929
- cbs.map(cb => cb(data)),
1930
- )
1931
- })
1932
- }
1933
-
1934
- test('callback was called', async () => {
1935
- expect.hasAssertions()
1936
- onSelect((data) => {
1937
- // should be called on select
1938
- expect(data).toBeTruthy()
1939
- })
1940
- // if not awaited, test will fail
1941
- // if you don't have expect.hasAssertions(), test will pass
1942
- await select(3)
1943
- })
1944
- ```
1945
-
1946
- ## expect.unreachable
1947
-
1948
- - **Type:** `(message?: string) => never`
1949
-
1950
- This method is used to assert that a line should never be reached.
1951
-
1952
- For example, if we want to test that `build()` throws due to receiving directories having no `src` folder, and also handle each error separately, we could do this:
1953
-
1954
- ```ts
1955
- import { expect, test } from 'vitest'
1956
-
1957
- async function build(dir) {
1958
- if (dir.includes('no-src')) {
1959
- throw new Error(`${dir}/src does not exist`)
1960
- }
1961
- }
1962
-
1963
- const errorDirs = [
1964
- 'no-src-folder',
1965
- // ...
1966
- ]
1967
-
1968
- test.each(errorDirs)('build fails with "%s"', async (dir) => {
1969
- try {
1970
- await build(dir)
1971
- expect.unreachable('Should not pass build')
1972
- }
1973
- catch (err: any) {
1974
- expect(err).toBeInstanceOf(Error)
1975
- expect(err.stack).toContain('build')
1976
-
1977
- switch (dir) {
1978
- case 'no-src-folder':
1979
- expect(err.message).toBe(`${dir}/src does not exist`)
1980
- break
1981
- default:
1982
- // to exhaust all error tests
1983
- expect.unreachable('All error test must be handled')
1984
- break
1985
- }
1986
- }
1987
- })
1988
- ```
1989
-
1990
- ## expect.anything
1991
-
1992
- - **Type:** `() => any`
1993
-
1994
- This asymmetric matcher matches anything except `null` or `undefined`. Useful if you just want to be sure that a property exists with any value that's not either `null` or `undefined`.
1995
-
1996
- ```ts
1997
- import { expect, test } from 'vitest'
1998
-
1999
- test('object has "apples" key', () => {
2000
- expect({ apples: 22 }).toEqual({ apples: expect.anything() })
2001
- })
2002
- ```
2003
-
2004
- ## expect.any
2005
-
2006
- - **Type:** `(constructor: unknown) => any`
2007
-
2008
- This asymmetric matcher, when used with an equality check, will return `true` only if the value is an instance of a specified constructor. Useful, if you have a value that is generated each time, and you only want to know that it exists with a proper type.
2009
-
2010
- ```ts
2011
- import { expect, test } from 'vitest'
2012
- import { generateId } from './generators.js'
2013
-
2014
- test('"id" is a number', () => {
2015
- expect({ id: generateId() }).toEqual({ id: expect.any(Number) })
2016
- })
2017
- ```
2018
-
2019
- ## expect.closeTo {#expect-closeto}
2020
-
2021
- - **Type:** `(expected: any, precision?: number) => any`
2022
-
2023
- `expect.closeTo` is useful when comparing floating point numbers in object properties or array item. If you need to compare a number, please use `.toBeCloseTo` instead.
2024
-
2025
- The optional `precision` argument limits the number of digits to check **after** the decimal point. For the default value `2`, the test criterion is `Math.abs(expected - received) < 0.005 (that is, 10 ** -2 / 2)`.
2026
-
2027
- For example, this test passes with a precision of 5 digits:
2028
-
2029
- ```js
2030
- test('compare float in object properties', () => {
2031
- expect({
2032
- title: '0.1 + 0.2',
2033
- sum: 0.1 + 0.2,
2034
- }).toEqual({
2035
- title: '0.1 + 0.2',
2036
- sum: expect.closeTo(0.3, 5),
2037
- })
2038
- })
2039
- ```
2040
-
2041
- ## expect.arrayContaining
2042
-
2043
- - **Type:** `<T>(expected: T[]) => any`
2044
-
2045
- When used with an equality check, this asymmetric matcher will return `true` if the value is an array and contains specified items.
2046
-
2047
- ```ts
2048
- import { expect, test } from 'vitest'
2049
-
2050
- test('basket includes fuji', () => {
2051
- const basket = {
2052
- varieties: [
2053
- 'Empire',
2054
- 'Fuji',
2055
- 'Gala',
2056
- ],
2057
- count: 3
2058
- }
2059
- expect(basket).toEqual({
2060
- count: 3,
2061
- varieties: expect.arrayContaining(['Fuji'])
2062
- })
2063
- })
2064
- ```
2065
-
2066
- :::tip
2067
- You can use `expect.not` with this matcher to negate the expected value.
2068
- :::
2069
-
2070
- ## expect.objectContaining
2071
-
2072
- - **Type:** `(expected: any) => any`
2073
-
2074
- When used with an equality check, this asymmetric matcher will return `true` if the value has a similar shape.
2075
-
2076
- ```ts
2077
- import { expect, test } from 'vitest'
2078
-
2079
- test('basket has empire apples', () => {
2080
- const basket = {
2081
- varieties: [
2082
- {
2083
- name: 'Empire',
2084
- count: 1,
2085
- }
2086
- ],
2087
- }
2088
- expect(basket).toEqual({
2089
- varieties: [
2090
- expect.objectContaining({ name: 'Empire' }),
2091
- ]
2092
- })
2093
- })
2094
- ```
2095
-
2096
- :::tip
2097
- You can use `expect.not` with this matcher to negate the expected value.
2098
- :::
2099
-
2100
- ## expect.stringContaining
2101
-
2102
- - **Type:** `(expected: any) => any`
2103
-
2104
- When used with an equality check, this asymmetric matcher will return `true` if the value is a string and contains a specified substring.
2105
-
2106
- ```ts
2107
- import { expect, test } from 'vitest'
2108
-
2109
- test('variety has "Emp" in its name', () => {
2110
- const variety = {
2111
- name: 'Empire',
2112
- count: 1,
2113
- }
2114
- expect(variety).toEqual({
2115
- name: expect.stringContaining('Emp'),
2116
- count: 1,
2117
- })
2118
- })
2119
- ```
2120
-
2121
- :::tip
2122
- You can use `expect.not` with this matcher to negate the expected value.
2123
- :::
2124
-
2125
- ## expect.stringMatching
2126
-
2127
- - **Type:** `(expected: any) => any`
2128
-
2129
- When used with an equality check, this asymmetric matcher will return `true` if the value is a string and contains a specified substring or if the string matches a regular expression.
2130
-
2131
- ```ts
2132
- import { expect, test } from 'vitest'
2133
-
2134
- test('variety ends with "re"', () => {
2135
- const variety = {
2136
- name: 'Empire',
2137
- count: 1,
2138
- }
2139
- expect(variety).toEqual({
2140
- name: expect.stringMatching(/re$/),
2141
- count: 1,
2142
- })
2143
- })
2144
- ```
2145
-
2146
- :::tip
2147
- You can use `expect.not` with this matcher to negate the expected value.
2148
- :::
2149
-
2150
- ## expect.schemaMatching
2151
-
2152
- - **Type:** `(expected: StandardSchemaV1) => any`
2153
-
2154
- When used with an equality check, this asymmetric matcher will return `true` if the value matches the provided schema. The schema must implement the [Standard Schema v1](https://standardschema.dev/) specification.
2155
-
2156
- ```ts
2157
- import { expect, test } from 'vitest'
2158
- import { z } from 'zod'
2159
- import * as v from 'valibot'
2160
- import { type } from 'arktype'
2161
-
2162
- test('email validation', () => {
2163
- const user = { email: 'john@example.com' }
2164
-
2165
- // using Zod
2166
- expect(user).toEqual({
2167
- email: expect.schemaMatching(z.string().email()),
2168
- })
2169
-
2170
- // using Valibot
2171
- expect(user).toEqual({
2172
- email: expect.schemaMatching(v.pipe(v.string(), v.email()))
2173
- })
2174
-
2175
- // using ArkType
2176
- expect(user).toEqual({
2177
- email: expect.schemaMatching(type('string.email')),
2178
- })
2179
- })
2180
- ```
2181
-
2182
- :::tip
2183
- You can use `expect.not` with this matcher to negate the expected value.
2184
- :::
2185
-
2186
- ## expect.addSnapshotSerializer
2187
-
2188
- - **Type:** `(plugin: PrettyFormatPlugin) => void`
2189
-
2190
- This method adds custom serializers that are called when creating a snapshot. This is an advanced feature - if you want to know more, please read a [guide on custom serializers](/guide/snapshot#custom-serializer).
2191
-
2192
- If you are adding custom serializers, you should call this method inside [`setupFiles`](/config/setupfiles). This will affect every snapshot.
2193
-
2194
- :::tip
2195
- If you previously used Vue CLI with Jest, you might want to install [jest-serializer-vue](https://npmx.dev/package/jest-serializer-vue). Otherwise, your snapshots will be wrapped in a string, which cases `"` to be escaped.
2196
- :::
2197
-
2198
- ## expect.extend
2199
-
2200
- - **Type:** `(matchers: MatchersObject) => void`
2201
-
2202
- You can extend default matchers with your own. This function is used to extend the matchers object with custom matchers.
2203
-
2204
- When you define matchers that way, you also create asymmetric matchers that can be used like `expect.stringContaining`.
2205
-
2206
- ```ts
2207
- import { expect, test } from 'vitest'
2208
-
2209
- test('custom matchers', () => {
2210
- expect.extend({
2211
- toBeFoo: (received, expected) => {
2212
- if (received !== 'foo') {
2213
- return {
2214
- message: () => `expected ${received} to be foo`,
2215
- pass: false,
2216
- }
2217
- }
2218
- },
2219
- })
2220
-
2221
- expect('foo').toBeFoo()
2222
- expect({ foo: 'foo' }).toEqual({ foo: expect.toBeFoo() })
2223
- })
2224
- ```
2225
-
2226
- ::: tip
2227
- If you want your matchers to appear in every test, you should call this method inside [`setupFiles`](/config/setupfiles).
2228
- :::
2229
-
2230
- This function is compatible with Jest's `expect.extend`, so any library that uses it to create custom matchers will work with Vitest.
2231
-
2232
- If you are using TypeScript, since Vitest 0.31.0 you can extend default `Assertion` interface in an ambient declaration file (e.g: `vitest.d.ts`) with the code below:
2233
-
2234
- ```ts
2235
- interface CustomMatchers<R = unknown> {
2236
- toBeFoo: () => R
2237
- }
2238
-
2239
- declare module 'vitest' {
2240
- interface Assertion<T = any> extends CustomMatchers<T> {}
2241
- interface AsymmetricMatchersContaining extends CustomMatchers {}
2242
- }
2243
- ```
2244
-
2245
- ::: warning
2246
- Don't forget to include the ambient declaration file in your `tsconfig.json`.
2247
- :::
2248
-
2249
- :::tip
2250
- If you want to know more, checkout [guide on extending matchers](/guide/extending-matchers).
2251
- :::
2252
-
2253
- ## expect.addEqualityTesters {#expect-addequalitytesters}
2254
-
2255
- - **Type:** `(tester: Array<Tester>) => void`
2256
-
2257
- You can use this method to define custom testers, which are methods used by matchers, to test if two objects are equal. It is compatible with Jest's `expect.addEqualityTesters`.
2258
-
2259
- ```ts
2260
- import { expect, test } from 'vitest'
2261
-
2262
- class AnagramComparator {
2263
- public word: string
2264
-
2265
- constructor(word: string) {
2266
- this.word = word
2267
- }
2268
-
2269
- equals(other: AnagramComparator): boolean {
2270
- const cleanStr1 = this.word.replace(/ /g, '').toLowerCase()
2271
- const cleanStr2 = other.word.replace(/ /g, '').toLowerCase()
2272
-
2273
- const sortedStr1 = cleanStr1.split('').sort().join('')
2274
- const sortedStr2 = cleanStr2.split('').sort().join('')
2275
-
2276
- return sortedStr1 === sortedStr2
2277
- }
2278
- }
2279
-
2280
- function isAnagramComparator(a: unknown): a is AnagramComparator {
2281
- return a instanceof AnagramComparator
2282
- }
2283
-
2284
- function areAnagramsEqual(a: unknown, b: unknown): boolean | undefined {
2285
- const isAAnagramComparator = isAnagramComparator(a)
2286
- const isBAnagramComparator = isAnagramComparator(b)
2287
-
2288
- if (isAAnagramComparator && isBAnagramComparator) {
2289
- return a.equals(b)
2290
- }
2291
- else if (isAAnagramComparator === isBAnagramComparator) {
2292
- return undefined
2293
- }
2294
- else {
2295
- return false
2296
- }
2297
- }
2298
-
2299
- expect.addEqualityTesters([areAnagramsEqual])
2300
-
2301
- test('custom equality tester', () => {
2302
- expect(new AnagramComparator('listen')).toEqual(new AnagramComparator('silent'))
2303
- })
2304
- ```