In my TypeScript project, decorators are a crucial part of enhancing method behavior. However, I recently ran into a situation where a decorator could potentially block the execution of a method. To test this scenario using Jest, I aim to confirm whether the decorated method was called or not.
Consider the following example of a class with a theoretical CacheDecorator:
class TestClass {
@CacheDecorator
async methodToTest(arg1: string, arg2: number) {
return { arg1, arg2 };
}
}
The CacheDecorator
assesses a cache and either returns a cached value without running methodToTest
, or allows methodToTest
to proceed if there is no valid cache entry.
I want to verify whether methodToTest
is executed based on the caching conditions. The challenge I face is distinguishing between the decorator's actions and the actual method call when attempting to spy on methodToTest
directly with jest.spyOn()
.
Is there an effective way to spy on methodToTest
to determine if it has been executed, considering the behavior of this particular decorator?