Creating a Jest TypeScript client mock that returns an array filled with undefined elements instead of the expected resolved values

At the moment, I am in the process of writing tests for a helper function that I created. This function takes a client and an array as parameters. Essentially, the function is designed to retrieve all tasks for all sites on a website. So far, the method is functioning correctly.

export async function getAllTasks(
  sites: Site[],
  client: Client
): Promise<Task[]> {
  try {
    return (
      await Promise.all(
        sites.map(async (site) => {
          return client.getTasks(site.id);
        })
      )
    ).flat();
  } catch (e) {
    throw new createError(400, 'Bad Request: Unable to get all site tasks');
  }
}
jest.mock('@src/client');
const mockClient = <jest.Mock<Client>>Client;

describe('Helpers', () => {
  const mockTask = createMock<Task>();

  mockClient.mockImplementation(() => {
    return {
      getTasks: jest.fn().mockReturnValue([mockTask]),
      ...mockClient.prototype
    };
  });

  it('getAllTasks()', async () => {
    const mockSites = [createMock<Site>()];
    const mockClient = new mockClient({
      // constructor params here
    });
    const tasks = await getAllTasks(mockSites, mockClient);
    expect(tasks).toEqual([mockTask]);
  });
});

A challenge has arisen during testing, resulting in failure with the following error:

 expect(received).toEqual(expected) // deep equality

    - Expected  - 5
    + Received  + 1

      Array [
    -   Object {
    -     "customerId": 0,
    -     "id": "",
    -     "siteId": "",
    -   },
    +   undefined,
      ]

The issue seems to be related to the mocked method returning an array with only one undefined element, causing the test to fail. Unraveling this problem might require some attention to detail, but I am struggling to identify the root cause. Any insights or assistance would be greatly appreciated. Thank you!

Answer №1

Hi there, I made a mistake in my implementation restructuring but have now corrected it. Below is the updated version for your reference.

mockClient.mockImplementation(() => {
    return {
      ...mockClient.prototype,
      getTasks: jest.fn().mockReturnValue([mockTask])
    };
  });

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

Passing a service into a promise in Angular 2 using TypeScript

Is there a way to pass a service into a promise? I am currently working on a promise that will only resolve once all the http requests are complete. However, I am facing an issue where this.jiraService is undefined. Is there a method to pass it to the co ...

Utilize the power of generics with Angular's service providers

Is it possible to make the membervar of class Parent generic instead of type any, while still retaining the ability to switch provider classes without having to update all components that rely on class Parent? For example, if class ChildB implements a diff ...

Discovering the world of Promises in TypeScript and understanding how to return specific types

Transitioning from coding in Clojure for the past two years to TypeScript has been an interesting journey. However, I've hit a bit of a roadblock today. The issue lies with my interface: interface ICustomer { id: number, first_name: string } I ...

What could be the reason for `process.env.myvariable` not functioning in a Next.js project with TypeScript

After creating a file called .env.local in the root directory of my project, I added a variable called WEBSOCKET_VARIABLE=THIS_IS_TEXT to it. However, when I try to access it using process.env.WEBSOCKET_VARIABLE, nothing is found. What could be causing ...

A deep dive into TypeScript: enhancing a type by adding mandatory and optional fields

In this scenario, we encounter a simple case that functions well individually but encounters issues when integrated into a larger structure. The rule is that if scrollToItem is specified, then getRowId becomes mandatory. Otherwise, getRowId remains option ...

Guide on utilizing map function and reassigning the value

I am facing a challenge with a list of books that have IsEnable defaulting to False. During onInit(), I need to check each book to see if it is enabled. I was considering using an rxjs map and calling the getEligibleBooks() function within the map, but I ...

Developing a Liferay 7.0 portlet using Angular and TypeScript

Is it possible to develop a Liferay 7.0 portlet using Angular (2, Angular Material v1.1.1) and TypeScript? I am aware that it is possible to incorporate Angular 1.4 library and create a portlet using plain JavaScript/Angular code, as mentioned in this sou ...

Steps for combining a sequence of subsequent subscriptions in RxJS

In my approach, I followed the code below. this.service1.info .subscribe(a => this.service2.getDetails(a.id) .subscribe(b => { this.doStuff(b); }) ); Lately, it has come to my attention that we will be adding more steps that gradu ...

No results from Django test database retrieval

I am encountering a similar issue to when the database gets destroyed in Django tests, where my test database is mysteriously getting wiped out between each method. Even though I know it's being cleared every time I run python3 manage.py test, it shou ...

Leveraging local resources to create images with the help of @vercel/og and Next.js

Utilizing the latest @vercel/og library for generating meta-tag images has been quite intriguing. The official example showcases how to leverage images from an external source. The Quandary at Hand <img src={"https://res.cloudinary.com/iqfareez ...

What is the reason for my algorithm's inability to work with this specific number?

I'm currently working on creating an algorithm to compute the sum of prime numbers that are less than or equal to a specified number. Below is my attempt: function calculatePrimeSum(num) { // initialize an array with numbers up to the given num let ...

How to troubleshoot the issue of "Error: (SystemJS) module is not defined" in Angular 2?

I am a beginner in the world of Angular2. It is known that in Angular2, there is a way to reference a file using a relative path by defining moduleId : module.id in the component meta data. However, I have tried doing it this way and keep encountering the ...

Creating nested routes with parameters in NestJS is a powerful feature that allows for dynamic routing

I have a requirement to create an API with routes that share a common URL part along with a parameter. For my particular case, the routes should follow this structure: /accounts/:account/resource1/:someParam /accounts/:account/resource2/:someParam/whate ...

When attempting to run a Typescript Playwright test in Visual Studio Code's debug mode, it inexplicably fails to execute

I am fairly new to TypeScript and Playwright, but I have experience in coding. I believe I have a good understanding of what I am trying to achieve, but I am encountering a problem that I can't seem to figure out. I'm hoping someone can help me. ...

The Value Entered in Angular is Unsaved

I have encountered an issue with my app's table functionality. The user can enter information into an input field and save it, but upon refreshing the page, the field appears empty as if no data was entered. Can someone please review my code snippet b ...

When using the TypeScript && operator, the resulting type is not determined by the second operand

Several past discussions on SO have touched upon the concept that the inferred type from && is based on the last expression. TypeScript’s failure to detect union type with an && operator Uncovering the reason behind the && opera ...

What is the best way to eliminate square brackets from keys within an array of objects in TypeScript?

I am currently working on a task to eliminate all square brackets from the keys in the entries field within an array of objects: data: [ {title: "Title1", entries: { 'Entry1': 333333, '[ABC]Entry2': 1234, 'Entry3' ...

"Despite the inability to use the clear input field function in Angular, users can still effectively clear

Why does the X button not clear and refresh the field when clicked, but using backspace does? I want it to clear when the X button is clicked. <mat-form-field appearance="standard" fxFill> <mat-label style="font-size: 12 ...

Even though the rxjs imports are correctly set up, the 'map' property is not found on the 'Observable<Response>' type

I'm currently developing a MEAN stack application using Angular 2. Despite finding similar inquiries on StackOverflow, I've explored various solutions without success. While many suggest importing the entire rx/js library along with map or using ...

What could be the reason for the variable's type being undefined in typescript?

After declaring the data type of a variable in TypeScript and checking its type, it may show as undefined if not initialized. For example: var a:number; console.log(a); However, if you initialize the variable with some data, then the type will be display ...