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/guide/mocking.md
+39-5
Original file line number
Diff line number
Diff line change
@@ -608,6 +608,10 @@ class Dog {
608
608
return'animal'
609
609
}
610
610
611
+
greet = ():string=> {
612
+
return`Hi! My name is ${this.name}!`
613
+
}
614
+
611
615
speak():string {
612
616
return'bark!'
613
617
}
@@ -622,18 +626,40 @@ We can re-create this class with ES5 functions:
622
626
```ts
623
627
const Dog =vi.fn(function (name) {
624
628
this.name=name
629
+
// mock instance methods in the constructor, each instance will have its own spy
630
+
this.greet=vi.fn(() =>`Hi! My name is ${this.name}!`)
625
631
})
626
632
627
633
// notice that static methods are mocked directly on the function,
628
634
// not on the instance of the class
629
635
Dog.getType=vi.fn(() =>'mocked animal')
630
636
631
637
// mock the "speak" and "feed" methods on every instance of a class
632
-
// all `new Dog()` instances will inherit these spies
638
+
// all `new Dog()` instances will inherit and share these spies
633
639
Dog.prototype.speak=vi.fn(() =>'loud bark!')
634
640
Dog.prototype.feed=vi.fn()
635
641
```
636
642
643
+
::: warning
644
+
If a non-primitive is returned from the constructor function, that value will become the result of the new expression. In this case the `[[Prototype]]` may not be correctly bound:
645
+
646
+
```ts
647
+
const CorrectDogClass =vi.fn(function (name) {
648
+
this.name=name
649
+
})
650
+
651
+
const IncorrectDogClass =vi.fn(name=> ({
652
+
name
653
+
}))
654
+
655
+
const Marti =newCorrectDogClass('Marti')
656
+
const Newt =newIncorrectDogClass('Newt')
657
+
658
+
MartiinstanceofCorrectDogClass// ✅ true
659
+
NewtinstanceofIncorrectDogClass// ❌ false!
660
+
```
661
+
:::
662
+
637
663
::: tip WHEN TO USE?
638
664
Generally speaking, you would re-create a class like this inside the module factory if the class is re-exported from another module:
0 commit comments