Replies: 2 comments 3 replies
-
It looks like this has been discussed in the past and Vitest doesn't automock getter/setter.
Can you show how you are doing this? Still a boilerplate, but creating a helper on your own might be a way to ease the process. import { test, vi } from "vitest";
import { SomeClass } from "./some-class";
// normal automocking + additional getters mocking
vi.mock("./some-class");
mockGetters(SomeClass.prototype);
// put this helper somewhere
function mockGetters(prototype) {
const descs = Object.getOwnPropertyDescriptors(prototype);
for (const [key, desc] of Object.entries(descs)) {
if (desc.get) {
vi.spyOn(prototype, key, "get").mockImplementation(() => {});
}
}
} |
Beta Was this translation helpful? Give feedback.
-
I've had this patch floating around ever since that PR got merged, since it broke our tests to have the getters just sitting there unmocked: diff --git a/node_modules/vitest/dist/vendor-execute.07d1a420.js b/node_modules/vitest/dist/vendor-execute.07d1a420.js
index c6f103b..ceb3a31 100644
--- a/node_modules/vitest/dist/vendor-execute.07d1a420.js
+++ b/node_modules/vitest/dist/vendor-execute.07d1a420.js
@@ -217,7 +217,9 @@ ${c.green(`vi.mock("${mockpath}", async () => {
for (const { key: property, descriptor } of getAllMockableProperties(container, isModule, this.primitives)) {
if (!isModule && descriptor.get) {
try {
- Object.defineProperty(newContainer, property, descriptor);
+ const mockedDescriptor = {};
+ mockPropertiesOf(descriptor, mockedDescriptor);
+ Object.defineProperty(newContainer, property, mockedDescriptor);
} catch (error) {
}
continue; You can use patch-package to apply it, but it is annoying to keep around since the hash suffix on the file changes with every new version. |
Beta Was this translation helpful? Give feedback.
-
I recently changes some of the class methods to be specifed as getters such as
To my surprise this broke the whole suit of tests as earlier when the methods were accessed as
someMethod()
instead of nowsomeMethods
we were just mocking the whole module and all class methods were automatically mocked which we then could check calls tho the methods and values for the arguments. Now I have to specifyspyOn
on every single method we have in our classes in order to have a spy/mock for getters.Is there a convenience method in Vitest to automatically spy on or mock all class getters, similar to how vi.mock can be used to mock a class's regular methods?
Beta Was this translation helpful? Give feedback.
All reactions