typescript mock extending interface

I'm currently working with a typescript interface called cRequest, which is being used as a type in a class method. This interface extends the express Request type. I need to figure out how to properly mock this for testing in either jest or typemoq.

import { Request } from 'express';
import { User } from '.';
export interface cRequest extends Request {
    context: {
        ID?: string;
        user?: string;
        nonUser?: string;
    };
    user?: User;
}
export default cRequest;

In my code, it's being utilized within a class method like this

import { Response } from 'express';
public getData = async (req: cRequest, res: Response) => {}

When attempting to test it as shown below, it fails

const expRespMock: TypeMoq.IMock<Response> = TypeMoq.Mock.ofType<Response>();
const cReqMock: TypeMoq.IMock<cRequest> = TypeMoq.Mock.ofType<cRequest>();
await classObj.getData(cReqMock, expRespMock);

The error message received is:

  Argument of type 'IMock<cRequest>' is not assignable to parameter of type 'cRequest'.
  Property 'context' is missing in type 'IMock<cRequest>'.

I need to find the correct approach to inject this interface mock into the method during testing.

Answer №1

Here is how I successfully tackled this issue

let requestData = <Request> {};

Now, I am able to customize the parameters injected without encountering any issues

let requestData = <Request> {user: undefined}; or
let requestData = <Request> {context: {ID: '', user: '', nonUser: ''}};

await serviceObject.fetchData(requestData, expectedResponseMock);

Answer №2

Why reinvent the wheel? Jest provides a way to enhance an existing interface with additional methods.

Here is an example:

interface IResponse {
   res: string;
}

responseMock: jest.Mocked<IResponse>;

The responseMock will include the IResponse interface along with mock interfaces.

A helpful tip for discovering new jest types is to explore the source code of the @types/jest library. For instance, examining the return type of jest.spyOn led me to discover jest.Mocked<>.

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

Unallocated functions found within Web Sockets Objects

I am currently utilizing javascript (p5.js) in combination with node.js using express and socket.io. Within my code, I believe the issue lies within this specific section: for (var i = 0; i < 3; i ++){ for (var j = 0; j < 3; j ++){ ...

Fill a JavaScript array with values inserted in the middle position

I'm having trouble populating an array: var arr2 = ["x", "y", "z"]; I want to insert a random number/value between each original value using a for loop, like this: for (let i = 1; i < arr2.length; i+2) { arr2.splice(i, 0, Math.random()); } B ...

Tips for managing JavaScript within PHP code and vice versa

Usually, I include a lot of JavaScript on the website. However, the client informed me that they were unable to view the website correctly as they had disabled JavaScript on their end. After investigating, I discovered this issue. Now, my dilemma is wh ...

attempting to retrieve a specific nested value using square brackets

I am attempting to track the position of an object associated with a particular row. Ultimately, I require a comprehensive object that includes both the row and the position of a "com" within that row. Below is my code snippet: (g represents a global objec ...

What is the best way to establish communication between methods in a React application?

In the SelectedTopicPage component, I currently have two methods: navigateNext and render. My goal is to pass the value of topicPageNo from the navigateNext method to the render method. What is the best way to achieve this in React? When I attempt to decla ...

Requesting AJAX page yields a null $_GET parameter

Content loaded dynamically via AJAX methods. The base page is index.php, and profile.php is the page that gets loaded. The jQuery code snippet below has nothing to do with an HTML request: $('<a/>', {href: '?userID='+post[' ...

What makes TypeScript believe that the variable could possibly be undefined when it is clearly not the case?

I recently encountered an issue where TypeScript incorrectly identifies a variable as possibly being undefined. Here is a simplified example: const func = (val1?: boolean, val2?: boolean) => { if (!val1 && !val2) return; let result: boolean; ...

Stop materializecss dropdown from closing when clicking within it

As I work on my current project, I am utilizing Materialize.css which includes a dropdown with various input forms inside. The dropdown can be closed by: clicking outside of .dropdown-content clicking inside of .dropdown-content clicking on .dropdown-bu ...

Discover the step-by-step process of combining an array with JSON to create the desired outcome

I am working with a JSON array that looks like this: var row={ shopId: 3, shopName: '1', address: 'abc', contactNumber: 1234 } Alongside, I have another array: var data= [ { imageId: 1, shopId: 3, imageUrl: 'aaa' }, ...

If the array in a React FOR loop changes but some of the keys remain the same, will all the components rerender?

I'm currently working on incorporating infinite scroll functionality for a series of videos. To differentiate each component, I am utilizing a unique identifier as the key. Given that each component will be quite sizable, my goal is to only display a ...

Using JavaScript and Tampermonkey to convert strings from an HTML element into an array

I am trying to change the names of months into numbers and place them in a table cell on a website. I thought using an array would make it easier to reference the month names by their corresponding array numbers, allowing me to add table tags before and af ...

Show the Array List in a left-to-right format

Is there a way to display an array list from left to right with a div scroll, instead of top to bottom? I am having trouble achieving this. Here is my demo code for reference. HTML <div> <h2 class="ylet-primary-500 alignleft">Sessions</h ...

There seems to be an issue with Node.js/Express: the page at /

Recently, I've been working on some code (specifically in app.js on the server). console.log("Server started. If you're reading this then your computer is still alive."); //Just a test command to ensure everything is functioning correctly. var ...

"Exploring the world of 3rd party libraries in Angular2 with Typescript and Webpack

I've begun working on a fantastic seed project that can be found at: https://github.com/AngularClass/angular2-webpack-starter However, I've encountered an issue with integrating third-party modules. Can anyone offer guidance on how to properly a ...

Guidelines for simulating ActivatedRouteSnapshot in observable testing situations

I am currently testing an observable feature from a service in Angular. This particular observable will output a boolean value based on the queryParam provided. For effective testing of this observable, it is essential to mock the queryParam value. Howev ...

What could be causing my div link to redirect to different content instead of the intended destination?

When creating a div to provide information about a course, including the price and a "Take Class" button that links to the purchase page, I encountered an issue where the link extends beyond the intended area. @import url(https://fonts.googleapis.com/cs ...

Utilizing Knockout to Render JSON List Items

Utilizing Knockout.js to dynamically update a view from JSON response has been my current focus. The structure of the JSON is as follows: var data = { "Properties": { "Engine Capacity": "1499cc", "Doors": 3, "Extras": [ "LED lights", ...

Here's how you can use welding techniques to attach objects and incorporate fin-like structures in THREE

I am currently working on a project involving a rocket ship orbiting various planets. To achieve this, I have started by creating my own rocket ship object and am aiming to model it similarly to this design: https://kyleagnew.files.wordpress.com/2018/02/lo ...

Mastering the Art of Incorporating jQuery, JavaScript and CSS References into Bootstrap with ASP.NET WebForms

Hey there, I'm currently working on a personal project as a beginner in Bootstrap. My main challenge for the past two days has been trying to integrate a dateTimePicker and number Incrementer using Bootstrap techniques. Despite my efforts in researchi ...

Implementing relative pathing in front-end development while using ExpressJS for the back-end

I'm currently in the process of developing an application with Express 4.14. When it comes to routing, I have a situation where the incoming request is "https://example.com/page", and I am using res.sendFile(__dirname + "/../client/pages/page/index.ht ...