Tips for simulating a decorator function applied to a method used in the system under test using JEST

I currently have a typescript class setup like this:

export class SystemUnderTest {

  @LogThisAction('something was done')
  public doSomething() {} 

}

It is clear that reflection is being used to execute a specific decoration function:

 export declare function LogThisAction(action: string): (target: any) => 
 void;

When running tests, I am not concerned with the actual implementation of the decorator function, so I attempt to mock it in this way:

 myModule = require(./DecoratorFunctions);
 myModule.LogThisAction = jest.fn();

However, this approach does not seem to be effective. Test results show:

● Test suite failed to run
TypeError: decorator is not a function
at DecorateProperty (node_modules/reflect-metadata/Reflect.js:553:33)

How can I accomplish my objective within the JEST framework?

Answer №1

Your decorator functions by returning another function, essentially making it a higher-order function.

Therefore, your mock is incorrect and it needs to return a function. You can fix it by using the following code:

const myModule = require('./DecoratorFunctions');
myModule.LogThisAction = () => jest.fn();

Answer №2

If you want to simulate the functionality of a module and its internal workings, you can utilize the

jest.mock

method.

jest.mock('./DecoratorFunctions', () => ({ LogThisAction: (item: any) => {
return (target, propertyKey, descriptor) => {
  // store the original method in a variable
  const originalMethod = descriptor.value as () => Promise<any>;
  descriptor.value = async function(...args) {
    originalMethod.apply(this, args);
    return response;
  };

  return descriptor;
}; }}));

By doing this, you can effectively imitate the behavior of the LogThisAction function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"JavaScript/jQuery: The pattern in the text does not align with the string

I am currently working on validating a text field with the specific data pattern of "I-MH-ABCD-ABC-1222". Below is the regular expression I have implemented, but unfortunately it is not functioning as intended. var router_added_sap = "I-MH-ABCD-ABC-1222" ...

Accessing the background page of a Chrome extension while it's in operation

I am in the process of developing my first chrome extension that allows youtube.com/tv to run in the background so it can be accessed easily on a phone or tablet. Everything is working fine, except for the fact that if I want to watch the video and not j ...

Unlocking the Power of CheerioJS for Selecting Table Elements

I am struggling to figure out how to use CheerioJS to parse HTML table values and convert them into a JSON object. Despite my efforts, I have only been able to come up with a convoluted solution that doesn't quite work. My goal is to extract informa ...

Is it possible to create a combined header/declaration file in Golang within a single file?

My goal is to automatically generate Golang declaration files based on .json data. While with TypeScript I can consolidate types/declarations in one file using namespaces, it seems more complex to achieve the same with Golang packages and namespacing. In ...

The length of video files created by MediaRecorder is not retained

This component prompts the user for camera access, displays a video preview, and allows the user to watch it again with video controls such as downloading or navigating to specific moments. However, there is an issue where the recorded video seems to be ...

By specifying the union type being used, the TypeScript compiler is informed

Imagine I have the following type: type TMyType = { a: string; b: number; c: number; d?: SpecialTypeA | SpecialTypeB | SpecialTypeC; } How can I specify in typescript that I am aware of the type of d in my (React) child components? I am hoping f ...

Error: React cannot render objects as children

I am encountering an error that I cannot seem to figure out. The issue seems to be with the following line of code: <p className="bold blue padding-left-30">{question}</p> Specifically, it does not like the usage of {question} in the above pa ...

Is there a way to use require in react-native to pass multiple images at once?

In my React Native project, I'm trying to upload multiple images and display them on a map. However, when I attempt to pass the URLs of local images to the map component, I encounter the following error: Error: Invalid call at line 62: require(url) ...

The challenges of dealing with duplicate identifiers caused by nesting npm packages in TypeScript

I am facing an issue with my project structure where I have a node_modules folder at the root level and another one within a subfolder named functions. The directory layout looks like this, ├── functions │   ├── index.js │   ├── ...

What steps can be taken to align the Three.js coordinate system with the DOM transform coordinates?

Can we adjust the position in Three.js to start at the top/left of the scene, similar to DOM elements? I want to create a sphere so that when the position is 0,0,0, it will be at the top left corner, with its size specified in CSS pixel dimensions that do ...

What could be causing my variables to not update in Node.js?

I recently developed a web application using node.js that is designed to receive messages from an SNS topic through a POST request. The messages are then logged to the console and displayed on the webpage. However, I noticed that when I publish a message t ...

What is the proper way to invoke a child method after converting an object from a parent class to a child class?

When we have a subclass B that overrides a method from its superclass A in TypeScript, why does calling the method on an instance of A result in the parent class's implementation being called? In TypeScript, consider a class called Drug with properti ...

Sending a prop to a handler causes issues with navigation paths

I'm facing an issue with my handler and button component setup. Here's my handler: const addToCartHandler = (id) => { navigate(`/cart/${brand}/${id}?qty=${qty}`)}; And here's the button component using the handler: <Button onClick={a ...

When an element is appended, its image height may sometimes be mistakenly reported as

I am dynamically adding divs and I need to retrieve the height and width of an image. Based on this information, I have to apply CSS to the MB-Container class. For example: if the image is portrait orientation, set container width to 100%. If it's ...

The Bootstrap modal stubbornly refuses to close even after resetting the HTML body

I am having an issue with my bootstrap modal where the closeModal button is not functioning properly after the printModal button has been clicked. The modal does not close as expected. Step 1: Click on the printModal button after the modal pops up (this w ...

Showing JSON Array Values in a Table

I have created an array and am attempting to display its values in a table. Initially, my solution only displayed a single value from the array that matched an exact ID. You can see this implementation at (). Entering "jjones" would yield a result. I then ...

What is the best way to ensure consistency in a value across various browsers using Javascript?

I am currently developing a feature on a webpage that displays the last update date of the page. The functionality I am aiming for is to select a date in the first input box, click the update button, and have the second box populate the Last Updated field ...

Challenges in handling asynchronous data within static JSON objects in Angular2

I have a service set up with some static objects that are being utilized in my UI. fetchRulesVariables() fetchRuleVariables() { let variables = [ { name: 'Credit Funding Type', id: 1, multiple: ...

Having trouble choosing elements with angular.element within ng-repeat loop

In my HTML code, I am using an ngRepeat element: <ol id="animationFrame"> <li ng-repeat="animationImage in animationImages" ng-repeat-listener> <img ng-src="{{animationImage.src}}" id="{{animationImage.id}}"> </li> </ol& ...

How can you deactivate all form elements in HTML except for the Submit button?

Is there a method available to automatically deactivate all form elements except the submit button as soon as the form loads? This would entail pre-loading data from the backend onto a JSP page while restricting user access for editing. Users will only be ...