Mock Classes without Decorators (e.g. @Controller() or @Injectable()) #637
Replies: 2 comments
-
|
Hi @schaeferto, Suites relies on metadata reflection, which means a class must be decorated with something like I'm curious about what you're trying to achieve with this setup. There might be a more elegant solution that fits your needs better. Could you provide more details on your use case? This way, I can help you find the best approach. |
Beta Was this translation helpful? Give feedback.
-
|
Hey @omermorad, export const createMock = <T>(methods: Partial<Record<keyof T, jest.Mock>> = {}): jest.Mocked<T> => {
const mock: any = {};
const handler = {
get: (target: any, prop: string) => {
if (!(prop in target)) {
target[prop] = jest.fn();
}
return target[prop];
},
};
const proxy = new Proxy(mock, handler);
for (const method in methods) {
proxy[method] = methods[method];
}
return proxy as jest.Mocked<T>;
};This way I can create my dependencies like this: const dependency1: jest.Mocked<DependencyType1> = createMock();
const dependency2: jest.Mocked<DependencyType2> = createMock();
const testObject = new TestObject(dependency1, dependency2);I can also pass an Object to createMock({}) with type hints etc. which is, what I needed. TestObject is a simple Class, no @Injectable(). |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hey guys,
I have one question and hope you could help me out here. Or at least push me into the right direction.
So, I would like to simply create a mock like you do in your example code:
But unlike in your example, I do not want to annotate the class SomeClassToMock with the DI annotations of nestjs, because I want to express, that the devs have to initialise this class with 'new' and not using DI.
If I would add the Injectable() annotation it starts working as expected.
Am I doing weird stuff here?
Could you please point out, why this is only working with the decorator on that class?
How would you create a mock of such a 'normal' - 'un-decorated' class? I thought about using suites for this because I like getting the type-hints inside the .final() and the auto-mocking of the dependencies from the constructor of the mocked class.
Thank you for any hints or comments!
Beta Was this translation helpful? Give feedback.
All reactions