Using Jest and Typescript to mock a constant within a function

Just getting started with Jest and have a question:

Let's say I have a function that includes a const set to a specific type (newArtist):

export class myTestClass {
    async map(document: string) {
        const artist: newArtist = document.metadata.artist;
        ...
        }
}

And I also have:

export interface newArtist {
    name: string;
    title: string;
}

Now for my test, if I try something like this:

it("Sample test", async () => {
    const result: any = await new myTestClass(__context()).map({
        name: "An Artist"
        title: null
    });
        ...
}

The test fails because title is set to null. I need the interface to allow null values for the test, like this:

export interface newArtist {
    name: string;
    title: string | null;
}

How can I achieve that? I've heard of mocking classes, but isn't that just copying and pasting the code from the map function?

Any guidance is appreciated.

Thank you.

Answer №1

I am a bit confused about what you are trying to accomplish. The code you provided seems to be incorrect.

Personally, I have had success using the following code with typescript and jest. Could you please provide more information?

index.ts:

export interface INewArtist {
  name: string;
  title: string | null;
}

export interface IDocument {
  metadata: {
    artist: INewArtist;
  };
}

export class MyTestClass {
  constructor(private readonly ctx) {}
  public async map(document: IDocument) {
    const artist: INewArtist = document.metadata.artist;
  }
}

Unit test:

import { MyTestClass, IDocument } from './';

// tslint:disable-next-line: variable-name
const __context = () => {};

describe('MyTestClass', () => {
  it('My example test', async () => {
    const document: IDocument = {
      metadata: {
        artist: {
          name: 'An Artist',
          title: null
        }
      }
    };

    const result: any = await new MyTestClass(__context()).map(document);
  });
});

Unit test result:

 PASS  src/stackoverflow/56847385/index.spec.ts
  MyTestClass
    ✓ My example test (3ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.396s

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 on showcasing lengthy string content from JSON in a structured list format using react with typescript

Is there a way to display long string data from a JSON file in a list format when the description string is too lengthy? How can I split or format the description using React and TypeScript? The JSON data I have is as follows: "options": [ ...

Define the interface for a GraphQL resolver argument in code-first implementation

This specific GraphQL schema example from the Constructing Types page showcases how to define the Query type. // Creating the Query type var queryType = new graphql.GraphQLObjectType({ name: 'Query', fields: { user: { type: userType ...

Combining declarations to ensure non-null assets

Let's modify this from @types/aws-lambda to clearly indicate that our intention is for pathParameters to not be null and have a specific format. export interface APIGatewayProxyEventBase<TAuthorizerContext> { body: string | null; headers ...

Tips for retrieving the generated ID from the server immediately following form submission using the Post method in TypeScript

When submitting a long-form, it is important to ensure that no data is lost. Users should be able to stay on the same page to make any necessary changes after clicking the submit button. I need to receive the unique id generated by the server upon submissi ...

Leveraging constructors for injecting dependencies in Angular is a key practice for enhancing modularity and maintainability

After reviewing the Angular Official documents and various blogs, I noticed that there are two different syntaxes for Dependency Injection (DI) when used within the constructor. Sometimes this is utilized, while other times it is not. This leads to the que ...

Encountering a NaN outcome when summing values from various select options

I'm working on a project that involves adding up the prices based on the surface chosen by the user. I'm struggling with calculating the partial cost when the user's choice changes. totalSum.ts num: Calculation totalAmount: number cate ...

Sharing the label element as a prop in React component

I encountered the following code snippet: <div className="input-field"> <label htmlFor="timeObjective">Time Objective</label> <FrequencySet label='label'/> //HERE </div> My goal is to tra ...

"Unexpected issue encountered while testing middleware in NextJS using Jest - the locale variable

Whenever I run my Jest test, the NextRequest object is consistently returning an undefined value for locale data (req.nextUrl.locale). An error occurs when I attempt to assign a value in my test: TypeError: The NextURL configuration includes no locale "en ...

Typescript: searching for a specific type within an array of objects

The title may be a bit unclear, but I'm struggling to find a better way to explain it. I have a predefined set of classes from a third-party library that I cannot modify. The specific content of these classes is not relevant, as it's just for i ...

Utilizing TypeScript with Vue3 to Pass a Pinia Store as a Prop

My current stack includes Typescript, Pinia, and Vue3. I have a MenuButton component that I want to be able to pass a Pinia store for managing the menu open state and related actions. There are multiple menus in the application, each using the same store f ...

What causes React JS to continuously render in an infinite loop when using hooks and useState

I am struggling with updating the current state of my component based on a result using a custom hook in React. Whenever I try to update it, I end up in an infinite loop rendering due to my usage of the useState() hook. I am still new to working with Rea ...

Issue with React Context Provider failing to set value

I am currently diving into React context hooks and encountering an issue that is puzzling me. I have established a user context with the simple string message of "hello user" as follows: import { useContext, createContext } from "react" export ...

The module '@ngmodule/material-carousel' could not be located

Having an issue with Angular 8 where I am encountering an error when trying to import the @ngmodule/material-carousel module. The specific error message is: Cannot find module '@ngmodule/material-carousel' Package.json "private": true, "depen ...

Creating an Angular form group that includes dynamic form controls with custom form control names

Seeking to implement a formGroup that dynamically adjusts based on JSON data like this: const LIMITS: Limit[] = [ { id: 'limit1', value: 1000, disabled: false }, { id: 'limit2', value: 500, disabled: tru ...

Error: Unable to dispatch a Redux-thunk action with additional arguments in React

Currently, I am attempting to work with TypeScript alongside Redux-Thunk and Redux. My goal is to pass an object to any action (I am utilizing dependency injection and need to pass either an object service or a string). However, I encountered the followin ...

Displaying decimal values in Angular as percentages

In my Angular application, I have a numeric textbox that displays a percentage value and allows users to update it. https://i.stack.imgur.com/eCOKe.png <label for="fees">Fees %</label> <div class="inpu ...

Exploring the functionalities of React Native with react-hook-form and implementing them with TypeScript

I've been working on creating a custom Input component in react native using typescript for the react-hook-form library. type CustomInputProps = { name: any, control: any } const CustomInput: FC<CustomInputProps> = ({name, control, ...p ...

JavaScript code that displays values that are not equal

Here is a code snippet that checks whether two arrays of objects are equal or not. How can we enhance this code to log which answer is not matching? The structure of the arrays: arrayA represents user answered questions, while arrayB contains correct answ ...

Developing a collection of components with customizable color variations using React

I am interested in creating a React component library where users can specify color variants. For instance, I want to use the following syntax: const customTheme = createCustomTheme({ button: { variants: { primary: 'primary ...

Angular6 table using *ngFor directive to display objects within an object

Dealing with Angular 6 tables and encountering a challenge with an item in the *ngFor loop. Here is my HTML view: <table class="table table-bordered text-center"> <tr> <th class="text-center">Cuenta</th> <th class="te ...