You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/api/mock.md
+41Lines changed: 41 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -50,6 +50,47 @@ fn.length // == 2
50
50
The custom function implementation in the types below is marked with a generic `<T>`.
51
51
:::
52
52
53
+
::: warning Class Support {#class-support}
54
+
Shorthand methods like `mockReturnValue`, `mockReturnValueOnce`, `mockResolvedValue` and others cannot be used on a mocked class. Class constructors have [unintuitive behaviour](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor) regarding the return value:
55
+
56
+
```ts {2,7}
57
+
const CorrectDogClass =vi.fn(class {
58
+
constructor(publicname:string) {}
59
+
})
60
+
61
+
const IncorrectDogClass =vi.fn(class {
62
+
constructor(publicname:string) {
63
+
return { name }
64
+
}
65
+
})
66
+
67
+
const Marti =newCorrectDogClass('Marti')
68
+
const Newt =newIncorrectDogClass('Newt')
69
+
70
+
MartiinstanceofCorrectDogClass// ✅ true
71
+
NewtinstanceofIncorrectDogClass// ❌ false!
72
+
```
73
+
74
+
Even though the shapes are the same, the _return value_ from the constructor is assigned to `Newt`, which is a plain object, not an instance of a mock. Vitest guards you against this behaviour in shorthand methods (but not in `mockImplementation`!) and throws an error instead.
75
+
76
+
If you need to mock constructed instance of a class, consider using the `class` syntax with `mockImplementation` instead:
`Cannot use \`${shorthand}\` when called with \`new\`. Use \`mockImplementation\` with a \`class\` keyword instead. See https://vitest.dev/api/mock#class-support for more information.`,
0 commit comments