Unable to simulate Paginate function in jest unit testing

Currently, I am in the process of mocking the findAll function of my service. To achieve this, I have to decide whether to mock the repository function findAndCount within myEntityRepository or the paginate function of the nestjs-typeorm-paginate node module. The findAll function is responsible for retrieving a list of records from a table and paginating them using the NodeModule nestjs-typeorm-paginate.

Attempt 1: Mocking myEntityRepository However, this attempt failed with the following error and traceback:

    TypeError: queryBuilder.limit is not a function

      at ../node_modules/nestjs-typeorm-paginate/dist/paginate.js:119:28
      at ../node_modules/nestjs-typeorm-paginate/dist/paginate.js:8:71
      at Object.<anonymous>.__awaiter (../node_modules/nestjs-typeorm-paginate/dist/paginate.js:4:12)
      at paginateQueryBuilder (../node_modules/nestjs-typeorm-paginate/dist/paginate.js:115:12)
      at Object.<anonymous> (../node_modules/nestjs-typeorm-paginate/dist/paginate.js:22:15)
      at ../node_modules/nestjs-typeorm-paginate/dist/paginate.js:8:71

my.service.ts

import { IPaginationOptions, paginate, Pagination } from 'nestjs-typeorm-paginate'

export class MyService {
  constructor(@InjectRepository(MyEntity) private myEntityRepository: Repository<MyEntity>) { }

  async findAll(options: IPaginationOptions): Promise<Pagination<MyEntity>> {
    try {
      return await paginate<MyEntity>(this.myEntityRepository, options)
    } catch (error) {
      throw error
    }
  }
}

my.service.spec.ts

describe('MyService Basic GET findAll test cases', () => {
  let service: MyService
  let repositoryMock: MockType<Repository<MyEntity>>

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [MyService,
        {
          provide: getRepositoryToken(MyEntity), useFactory: repositoryMockFactory
        }
      ],
    }).compile()

    service = module.get<MyService>(MyService)
    repositoryMock = module.get(getRepositoryToken(MyEntity))

    const itemList = [{
        id: 1,
        my_field: 'a1',
    }, {
        id: 2,
        my_field: 'a2',
    }, ]

  it('should findAll() the MyEntity', async () => {
    expect((await service.findAll(options)).items.length).toBe(itemsList.length)
  })
})

const repositoryMockFactory: () => MockType<Repository<MyEntity>> = jest.fn(() => ({
  find: jest.fn(entity => entity),
  findAndCount: jest.fn(entity => entity),
}))

Attempt 2: Mocking paginate I then attempted to mock the paginate method, but encountered another error:

    TypeError: Cannot redefine property: paginate at Function.defineProperty (<anonymous>)

my.service.spec.ts with Pagination mock changes)

import * as nestjsTypeormPaginate from 'nestjs-typeorm-paginate' // imported at top
  ....
  ....
  it('should findAll() the MyEntity', async () => {
    const queryDto: QueryMyEntityDto = { customerId: 1 }
    const options: IPaginationOptions = { page: 1, limit: 10 }
    let paginationMock = jest.spyOn(nestjsTypeormPaginate, 'paginate')
    paginationMock.mockImplementation((dto, options) => Promise.resolve({
      items: itemList.slice(0, 2),
      meta: {
        itemCount: 2,
        totalItems: 2,
        totalPages: 1,
        currentPage: 1,
      }
    }))
    repositoryMock.find.mockReturnValue(itemList)
    expect((await service.findAll(options)).items.length).toBe(itemsList.length)
  })
  ...

Before posting this question: I explored the following resources:

  1. Utilizing `jest.spyOn` on an exported function from a Node module
  2. How to mock an imported named function in Jest when the module is unmocked
  3. https://github.com/nestjsx/nestjs-typeorm-paginate/issues/143

Answer №1

I was able to resolve the issue by simulating the external module in a different manner:

my.service.spec.ts

// To better handle the issue in your unit test file, ensure to include this code snippet before importing the service

// Define the items in your itemList
const itemList = ['item1', 'item2', 'item3', 'item4'];

// Create a mock for the external module and the paginate function
jest.mock('nestjs-typeorm-paginate', () => ({
  paginate: jest.fn().mockResolvedValue({
      items: itemList.slice(0, 2),
      meta: {
        itemCount: 2,
        totalItems: 2,
        totalPages: 1,
        currentPage: 1,
      }
    }),
}));

// ... carry out unit tests

This approach proved to be effective in my specific case. I found inspiration from .

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 synchronizing the display of a table with the server response in an Angular application

* Project I am currently working on a project that involves retrieving player data from a json server and displaying it in a standard table format with a paginator. * Issue The challenge I'm facing is ensuring that the table data is loaded before th ...

Using TypeScript to handle text resolution through the command line interface

Currently, I am developing a CLI application using TypeScript and employing enquirer for the purpose. More information about enquirer can be found here. In my project, I have a JSON object defined as follows: const person = { name: 'Mohan', ...

Unable to utilize the forEach() function on an array-like object

While I generally know how to use forEach, I recently encountered a situation that left me puzzled. Even after searching online, I couldn't find any new information that could help. I recently started delving into TypeScript due to my work with Angul ...

Ways to conduct testing on React Native Typescript app COMPONENTS using jest

I've been struggling to set up testing for my React Native Typescript Components using Jest. Despite searching through various examples and solutions (such as this one, that one, another link, etc.), I still can't seem to get it working. Even fol ...

Can someone explain how to define "a type of object that must not be empty" in typescript?

I'm working with a function that can operate on any type T, but with the constraint that if T is an object, it cannot potentially be empty. Here's what I've tried: declare function myFunction<T>(param: T extends Record<string, neve ...

Does Angular 1.3.x have a corresponding .d.ts file available?

Is there a .d.ts file available for Angular 1.3.x to assist in transitioning an app to Typescript 2.0? ...

What is the process for transforming a string literal type into the keys of a different type?

Imagine having a string literal type like this: type Letters = "a" | "b" | "c" | "d" | "e"; Is there a way to create the following type based on Letters? type LetterFlags = {a: boolean, b: boolean, c: bool ...

Is it possible for an uninitialized field of a non-null literal string type to remain undefined even with strict null checks in

It seems that there might be a bug in Typescript regarding the behavior described below. I have submitted an issue on GitHub to address this problem, and you can find it at this link. The code example provided in that issue explains the situation more clea ...

Encountering difficulty in fetching data from a service with ng-select

Currently, I am utilizing ng-select for a form that allows users to search for activities to add. The ng-select component triggers a function whenever something is typed into the field. This function then calls a service that fetches an array of activities ...

Discovering the type of a generic class in TypeScript

Class B extends a generic class A, and I am trying to infer the generic type of A that B is extending. The code snippet below demonstrates this. In earlier versions of TypeScript, this worked correctly for me. However, in my current project using version ...

What is the best way to stay on track with internal anchor links when navigating with Aurelia?

I'm currently working on developing a style guide for a project and one of the features I would like to implement is a basic click behavior on anchor links, allowing them to smoothly scroll to the corresponding section on the page. For instance: < ...

Switching the color scheme while utilizing React Context and MaterialUI

Currently, I'm attempting to implement a toggle feature for switching between dark and light modes using a custom palette in MaterialUI. Unfortunately, I'm encountering Type errors related to the value and theme props for the context provider and ...

The result should display the top 5 application names based on the count property found within the ImageDetails object

data = { "ImageDetails": [ { "application": "unknownApp, "count": 107757, }, { "application": "app6", "count": 1900, }, { & ...

Encasing distinct HTML text with a custom color palette

How can I create a specific color scheme for my HTML table's Status parameter, where the values can be SUCCESS, FAILURE, or IN PROGRESS? I'm utilizing Angular 4 (HTML and TypeScript) for this task. Any tips on how to achieve this? ...

Tips for integrating Typescript Definition files with Visual Studio 2017

I have a challenge with my ASP.NET Core 2.0 application where I am attempting to incorporate TypeScript and jQuery. While TypeScript integration has been successful, I am facing issues with jQuery as it does not provide me with intellisense. Despite trying ...

Issue with migrating TypeOrm due to raw SQL statement

Is it possible to use a regular INSERT INTO statement with TypeOrm? I've tried various ways of formatting the string and quotes, but I'm running out of patience. await queryRunner.query('INSERT INTO "table"(column1,column2) VALUES ...

Iterating through a for loop in Angular2 to send multiple GET requests to a Django backend

Currently, I'm facing a challenge with performing multiple GET requests using Angular2 within a Django/Python environment. After successfully making an API request and retrieving a list of users to determine the current user's ID, I utilize a .f ...

Tips for dynamically accessing object properties in TypeScript

I've been going through the process of converting existing Node.js projects to TypeScript. As part of this, I am utilizing the http-status package (https://www.npmjs.com/package/http-status) for handling HTTP status codes. While trying to pass varia ...

Execute a selector on child elements using cheerio

I am struggling to apply selectors to elements in cheerio (version 1.0.0-rc.3). Attempting to use find() results in an error. const xmlText = ` <table> <tr><td>Foo</td><td/></tr> <tr><td>1,2,3</td> ...

populating an array with objects

I am working with an array of objects var photos: Photos[] = []; The structure of Photos [] is as follows interface Photos { src: string; width: number; height: number; } I have a component that requires an array of strings export type PhotosArr ...