Generating fake data from MongoDB to meet TypeScript requirements in Jest testing

Currently, I am in the process of developing TypeScript interfaces for each model that extends mongoose.Document.

import mongoose, { Document } from 'mongoose';

export interface IAccount extends Document {
  _id: mongoose.Types.ObjectId;
  name: string;
  industry: string;
}

After defining the schema, it is then exported along with the interface:

export default mongoose.model<IAccount>('Account', accountSchema);

One issue encountered while testing with Jest is that simply creating an object with the necessary properties for the function being tested results in TypeScript raising errors due to missing fields.

function getData(account: IAccount){
  return account;
}

const account = {
  name: 'Test account name',
  industry: 'test account industry'
}

getData(account);

The error message received is 'Argument of type '{ name: string; industry: string; }' is not assignable to parameter of type 'IAccount'. Type '{ name: string; industry: string; }' is missing the following properties from type 'IAccount': _id, increment, model, and 52 more.ts(2345)'

What would be the most straightforward method to create an object that meets TypeScript requirements for testing purposes?

Answer №1

Creating a mock to match the expected type can be a valid approach...

...however, this task might become challenging especially for complex types.

Alternatively, you can inform TypeScript that you intend for your mock to undergo compile-time type validation.

This can be achieved by declaring your mock with the any type:

function fetchData(customer: ICustomer){
  return customer;
}

const customer: any = {  // <= specify type as "any"
  name: 'Example customer name',
  age: 25
}

fetchData(customer);  // <= no compilation error

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

Is it possible to define a data type from an external package using TypeScript and Node.js?

I'm currently in the process of reorganizing some code to utilize a list of signals and connect `.once` handlers to each one individually. const terminationSignals = ["SIGINT", "SIGUSR2", "SIGTERM"]; terminationSignals.f ...

What is the best way to verify a numerical input in a React component?

When I use the return statement, I attempt to validate a number and if it's not valid, assign a value of 0. However, this approach doesn't seem to be working for me. Is there an alternative method to achieve this? return ( <Input col ...

Implementing Routes in Express Using Typescript Classes

Seeking assistance in converting a Node.js project that utilizes Express.js. The objective is to achieve something similar to the setup in the App.ts file. In pure Javascript, the solution remains unchanged, except that instead of a class, it involves a mo ...

TS: Obtain specific typing for each generic child

Picture a scenario where the type of one property is determined by the value of another property For example, there is a planet with two countries: if your child is born in 'onename land', their name should be a single string; but if they are bo ...

Can someone provide an explanation of the Typescript peerDependencies in Angular, specifically comparing versions tslib 1.* and 2.3.*?

I am in the process of starting a new angular project, but I'm facing difficulties in importing the localStorage feature. I referred to an existing project that utilized localStorage in the following way: import { Injectable } from '@angular/core ...

Analyzing the efficiency of MongoDB aggregation's $group stage with $top versus $first on a massive data set

I am dealing with a vast data set (hundreds of millions) consisting of documents stored in Mongo 7.0. While the actual documents have more fields, I am focusing on the specific ones related to this query. { "groupId": "12345", "a ...

Display JSON data in a table format using Angular

I have received a JSON result that looks like this: { "discipline":"ACLS", "course": [ { "value":"ACLS Initial", "classes":"0", "students":"0" }, { "BLS":"CPR Inst ...

Validating object values prior to adding a key

How can we add a new key-value pair called partnerCam to the res.items objects when partnerTermStart and partnerTermEnd are not null? If partnerTermStart and partnerTermEnd have values, then we should insert a new key called partnerCam with a value calcul ...

Exploring Typescript code through a practical example with reference to Uniswap's implementation

On the Uniswap website, I came across some code on the Swap page that caught my attention. You can find the code snippet in question at line 115 of the Uniswap GitHub repository. const { trade: { state: tradeState, trade }, allowedSlippage, cur ...

How can I retrieve a client's IP address programmatically with Python?

db.currentOp(true).inprog.forEach(function(d){if(d.client)print(d.client, d.connectionId)}) Result: 127.0.0.1:64629 383 127.0.0.1:56878 363 I utilized this code snippet to retrieve the IP address of a client in the shell environment. Is there an alternat ...

"Enhance your MongoDB collection by dynamically adding a field based on the presence

I have a Job collection structured like this { "_id" : ObjectId("5b6aecd49bcdb5d4ae64ae5d"), "jobID" : "1", "jobStatus" : "active", "jobEndsDate" : ISODate("2018-08-15T23:59:59.014Z") } { "_id" : ObjectId("5b6aed179bcdb5d4ae64ae99"), ...

What is the best way to convert an array of data into a dataset format in React Native?

Within my specific use case, I am seeking to reform the array structure prior to loading it into a line chart. In this context, the props received are as follows: const data = [26.727, 26.952, 12.132, 25.933, 12.151, 28.492, 12.134, 26.191] The objective ...

Is there a possibility that typescript decorators' features will be polyfilled in browsers lacking ES5 support?

According to the typescript documentation, a warning is issued: WARNING  If your script target is lower than ES5, the Property Descriptor will be undefined. If the method decorator returns a value, it will act as the Property Descriptor for the method. ...

Exploring Nested <Routes> with ReactJs

My decision on whether to display the Foo page or the Bar page is based on the route. However, the Foo page itself contains two sub-routes for components to render depending on the URL path - such as FooOne or FooTwo. This results in having two layers of r ...

Enhancing Hapi.js server functions with TypeScript: A guide

One way to enhance the functionality of the hapi module by adding type checking for server methods is shown in the following code snippet: import { Server } from 'hapi'; declare module 'hapi' { export interface Server { m ...

Creating a unified object from faceted results in MongoDB: Streamlining keys and values for easy access

I'm currently working on a query to determine the equipment required by teams at specific times. By analyzing the list of teams and their allocated equipment, I aim to calculate the total equipment in use at any given moment. The team data looks like ...

Exploring the functionality of the mongoose find() method in node.js by searching for specific key value

Is there a way to retrieve data from a mongodb using the find() function while considering the schema below? const newcontractSchema = mongoose.Schema({ creator: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: false ...

Is there a way to make the Sweetalert2 alert appear just one time?

Here's my question - can sweetalert2 be set to only appear once per page? So that it remembers if it has already shown the alert. Swal.fire({ title: 'Do you want to save the changes?', showDenyButton: true, showCancelButton: true, ...

Using Vanilla JavaScript library in Angular 6 - A Comprehensive Guide

I encountered an error while trying to import a Vanilla JavaScript library into an Angular 6 component. Can you please provide me with some guidance on how to resolve this issue? This is the syntax I used to import the library: import * as ExistingLibrar ...

Module error caused by Typescript path inconsistency

After creating a new model named "project" within the existing project, I encountered an error when attempting to import the class into another typescript file in VS2019. The specific error message thrown is as follows: "ts2307 cannot find module ' ...