Creating dummy objects from a specific data type in Typescript for the purpose of testing

I'm exploring ways to streamline the creation of mock data for unit testing within an Angular solution. Currently, I am defining interfaces such as:

export interface ReferenceDataItemCommon {
  codeDescription?: string;
  code: string;
  deleted?: boolean;
}

These interfaces are used as data types in our application. At the moment, I am using Factory.ts along with Faker to generate fake objects for testing purposes:

  export const fakeReferenceDataItemCommon = Factory.Sync.makeFactory<ReferenceDataItemCommon>({
    code: Factory.each(() => Faker.lorem.word()),
    codeDescription: Factory.each(() => Faker.lorem.sentence(4)),
  });

However, I am interested in simplifying this process further to quickly create objects for testing purposes. Is it feasible in Typescript to have a generic method that can return an object of a specific datatype?

const fake = createFake<ReferenceDataItemCommon>();

My initial idea involves iterating through keys of an object and generating random values based on the type. For more complex objects, the method would be called recursively. Is this approach possible, and if so, what would be a better way to implement it as I'm feeling a bit overwhelmed by the concept?

Answer №2

After searching extensively for a similar solution without success, I decided to take matters into my own hands. That's why I developed the lib https://www.npmjs.com/package/class-validator-mocker. This library is designed to work seamlessly with classes that are annotated using class-validator decorators. If you're open to using data classes instead of interfaces to define specific types, I recommend checking it out.

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

Tips for updating the value within a textfield in HTML

I am looking to dynamically update the value displayed in my Revenue textfield by subtracting the Cost of Goods from the Sales Price. I have included an image of the current layout for reference, but I want the Revenue field to reflect the updated value af ...

Typescript controller inheritance leading to Error: $injector:unpr Unknown Provider due to minification

LATEST UPDATE: 2019/07/16 The issue I am facing is actually a result of misusing $inject. Instead of declaring it as private $inject in api-service.ts, it should have been public static $inject = [...]. During the minification process, explicit injection ...

Tips on accessing controller scope while testing a directive with isolate scope

Is it correct to write unit tests for a directive with isolate scope and controller, as well as test some functionality within the controller's scope? If so, how can access be gained to the controller scope? angular.module('myApp').dire ...

Angular outputting a basic static value

After searching extensively for a solution to my issue with Angular output, I have only come across ways to emit events. In my specific scenario, I have a parent component containing a router, and I need to dynamically change the title based on a value f ...

Ways to conceal a table and button in the absence of data for display

I've been working on a way to hide the table and the 'changeState' button when there's no data present. Currently, I have set it up so that a message saying 'No entries in the list!' pops up briefly before disappearing, bringi ...

Printing with Angular 2+ using ngx-print extension can be done manually by

Is there a way to print a div in Angular +2 using ngx-print, without automatically triggering the print function through a button attribute like ngxPrint? <button printSectionId="print-section" (click)="printProcedure()">print</button> ...

Concerns with combining key value pairs in Typescript Enums

Could you help me figure out how to properly implement an enum in my drop-down so that I can only display one value at a time? Currently, I am seeing both the key and the value in the list. This is my enum: export enum VMRole { "Kubemaster" = 0, "Kub ...

Retrieving data from Redis cache may not always yield the exact same data

I have been working on creating a small Express app that retrieves data from a PostgreSQL query and caches the result in a Redis database. Here is my approach: app.get('/query_tile/:z/:x/:y', async (req: Request, res: Response) => { const ...

The best location to place a main.scss file within an Angular 2 project

I'm wondering where the best place is to put a main.scss file so that it can be utilized by all components. I attempted to place the css in app.component.ts (root component), but the styles weren't being applied to one of my components. Issue Re ...

Include type declarations for property values that resemble arrays in a generic object

Imagine you have a function that: receives an object with multiple properties and a property name; checks if the property holds an array; if it does, performs an action (such as printing the values it contains) Here's an illustration: function pro ...

Can you explain the concept of injection context within Angular version 16 and later?

I have come across the term "Injection context" and am trying to understand what it entails. In Angular, there are several things that are connected to injection context: EnvironmentInjector#runInContext injectionContext runInInjectionContext inject() Fr ...

The recent upgrade to Angular 5 causes an error stating that the @angular/compiler-cli version must be 2.3.1 or higher, however the current version is 5.1.0

I am looking to enhance angular 4 within asp.net core2 and transition to angular 5 (the latest version) These are the steps I've taken: dotnet new angular npm install @angular/animations@latest @angular/common@latest @angular/compiler@latest @ ...

Guide on how to "attach" the routes of an Angular 2 module to a specific location within the routing structure

Let's consider a scenario where the main routing module is defined as follows: // app-routing.module.ts const appRoutes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'auth', ...

String interpolation can be used to easily accept numbers with dot separators

Is it possible to create a function that can accept numbers with dot separators? Here are some examples: func('100.000.002.333') // should pass func('10') // should pass func('20') // should pass func('100') // shou ...

Angular: Implementing conditional HTTP requests within a loop

Currently, I am facing a challenge where I need to loop through an array of objects, check a specific property of each object, and if it meets certain criteria, make an HTTP request to fetch additional data for that object. The code snippet below represen ...

JavaScript: Manipulating Data with Dual Arrays of Objects

//Original Data export const data1 = [ { addKey: '11', address: '12', value: 0 }, { addKey: '11', address: '12', value: 0 }, { addKey: '12', address: '11', value: 0 }, { addKey: &a ...

Invoking a Typescript function from the Highcharts load event

Struggling to call the TypeScript function openDialog() from the events.load of Highcharts? Despite using arrow functions, you are running into issues. Take a look at the code snippet below: events: { load: () => { var chart : any = this; ...

Visual Studio Code is encountering issues when trying to start a Node application

I am in the process of setting up a workflow for an express app using TypeScript, Visual Studio Code, and gulp. Here is the structure of my project: src/ <-- source files Start.ts Server.ts models/ Contact.ts Organization.ts bin/ <- ...

Displaying a collection of objects in HTML by iterating through an array

As someone new to coding, I am eager to tackle the following challenge: I have designed 3 distinct classes. The primary class is the Place class, followed by a restaurant class and an events class. Both the restaurant class and events class inherit core p ...

Is there a way to display the text that has been selected?

I would like to display the text of a clicked link in an empty div element. Can someone help me achieve this? Thank you. <div></div> <span>link one</span> <span>link two</span> <span>link three</span> ...