What is the best way to modify the return method in a got.post() function (using jest mock) in order to be able to

I attempted to utilize Jest for testing my TypeScript script

// api.ts
import got from "got";

export const run = async () => {
  const body = await got.get('https://jsonplaceholder.typicode.com/posts/1').json();
  return body;
};

Here is my test:

// api.test.ts
import { run } from "../api";
import got from "got";
import { mocked } from "ts-jest/dist/util/testing";

jest.mock("got");

test("using another got", async () => {
  const response = {
    get: jest.fn(),
  };
  mocked(got).mockResolvedValue(response);

  const result = await anotherGot();
  console.log(result);
  // expect(result).toBe(response.body);
});

However, when I tried running the test (npm test), I encountered an error:

TypeError: Cannot read property 'json' of undefined

What is the best approach to handle this issue in a Jest test?

Answer №1

In order to properly mock the function got.get, you must ensure that you are mocking the correct function and not just got itself. The Got npm package provides two ways of making HTTP GET requests:

  1. const response = got('http://google.com', { method: 'get' });
  2. const response = got.get('http://google.com');

Therefore, if you wish to mock your got.get(...) function, make sure to target got.get specifically, as shown in usecase #2 below:

// api.test.ts
// import { run } from "../api";
import got from "got";
import { mocked } from "ts-jest/utils";

jest.mock("got");

test("using another got", async () => {
    const mockedGot = mocked(got);

    // use case #1 - using got module directly
    mockedGot.mockReturnValue({
        json: () => Promise.resolve({ dataAttr1: 'val11111' }),
    } as any)

    const response1 = got('http://www.google.com', { method: 'get' });
    const data1 = await response1.json();
    expect(data1).toEqual({ dataAttr1: 'val11111' })

    /*******************************************************************/

    // use case #2 - using got.get "alias"
    // this is your case :)
    mockedGot.get = jest.fn().mockReturnValue({
        json: () => Promise.resolve({ dataAttr1: 'val22222' }),
    } as any);

    const response2 = got.get('http://www.google.com');
    const data2 = await response2.json();
    expect(data2).toEqual({ dataAttr1: 'val22222' })
});

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

The clarity of JS invariants may be questionable

Why does the invariant function have these parameters: function(condition, format, a, b, c, d, e, f) { instead of: function invariant(condition : any, format?: string, ...args : Array < any >) { Could someone please explain this to me, as it does ...

Is it Beneficial to Combine jQuery with TypeScript in Angular 7?

Our school project team is venturing into the world of Angular and TypeScript, but we all admit to being newbies in this area. I've mainly focused on the design aspect of our project and left the coding to my teammates. However, I recently completed ...

Show just a single error message if there are two validation errors present

In my AngularJS timepicker, users can choose multiple time segments for each day. The code has validation to detect duplicates and overlapping time segments. For example, entering 11:00am - 12:00am twice will trigger two error messages: 'Overlapping t ...

Exploring the possibilities with Rollbar and TypeScript

Struggling with Rollbar and TypeScript, their documentation is about as clear as AWS's. I'm in the process of creating a reusable package based on Rollbar, utilizing the latest TS version (currently 4.2.4). Let's delve into some code snipp ...

Implementing a custom type within a generic function

Struggling with a particular problem, I am trying to figure out whether it is possible to pass a custom type or if only native TypeScript types (such as string and number) can be passed into a generic type implementation for an interface: type coordinates ...

Failure to nest interfaces in Angular when mapping JSON responses

After calling my ASP.NET Core Web API, the JSON response appears as: [ { "driver": { "firstName": "TEST", "lastName": "LAST", "assignedRoute": "O_ROUTE" } }, { "driver": { "firstName": "First", "lastName": " ...

All-encompassing NextJS App router with a focus on Internationalization

I am currently working with a folder structure that includes an optional catch-all feature. The issue I am facing is that the page does not change when the URL is altered to include ""/"" or ""/about-us"". It consistently remains on the ...

Error: Import statement is not allowed outside a module - Issue with Jest, Typescript in a React environment

Whenever I attempt to execute 'npm test', a troubling error arises. The command in my package.json file is as follows: "test": "jest --config ./config/jest/jest.config.ts", SyntaxError: Cannot use import statement outside a module 1 | import a ...

Uh-oh! Angular 6 has encountered an unexpected error with template parsing

I am currently working on an Angular application where I have integrated the FormsModule from '@angular/forms' in my app.module.ts. However, despite this, I keep encountering the error message No provider for ControlContainer. Error log: Uncaug ...

The historical state pushed through history is not accessible in the redirected class

Having a scenario where I need to redirect from one page to another and pass the state as a prop to the redirected page. I've utilized history.push and attempted to access it using console.log(this.props.location.state.searchString) but encountering a ...

The tRPC setData hook is limited in its ability to access all data necessary for optimistic UI updates

As I integrate mutations using tRPC and React Query to optimistically update my UI upon adding a new item, I've encountered an issue. The problem lies in the query I'm updating, which requires specific properties like auto-generated IDs or datab ...

Troubleshooting a HTML error in Angular: How to pass data from Parent component to Child Component

In this scenario, I am passing data from a parent component to a child component in order to draw graphs using the provided information. The method responsible for drawing the graph is located within the child component and is called createGraph(divName, c ...

When attempting to send a token from an account to a marketplace in ERC721, the transfer caller must either be the owner

Currently, I am in the process of transferring my NFT to a marketplace pragma solidity ^0.8.7; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import & ...

A practical guide to effectively mocking named exports in Jest using Typescript

Attempting to Jest mock the UserService. Here is a snippet of the service: // UserService.ts export const create = async body => { ... save data to database ... } export const getById = async id => { ... retrieve user from database ... } The ...

When it comes to dealing with signature overload, the behavior of Record and Map may not align

This scenario may seem straightforward, but it's causing confusion. I have a function with an overloaded signature that can accept either a Record or a Map. However, even though I am passing a Map as an argument, TypeScript is treating it as a Record. ...

How can you check the status of a user in a Guild using Discord JS?

Is there a way to retrieve the online status of any user in a guild where the bot is present? Although I can currently access the online status of the message author, I would like to be able to retrieve the online status of any user by using the following ...

Encountered an eas error during Android build process

When I try to execute the command "eas build --platform android" I encounter the following error message: "✖ Build failed ...

Retrieving the name of the current page in ionViewCanEnter

While working with Ionic 2, I am currently facing a challenge in identifying the name of the page that triggered the navigation (PUSHER) before entering the destination page (PUSHEE). Within the PUSHEE page, I have an ionViewCanEnter function where I need ...

Error: Certain Prisma model mappings are not being generated

In my schema.prisma file, I have noticed that some models are not generating their @@map for use in the client. model ContentFilter { id Int @id @default(autoincrement()) blurriness Float? @default(0.3) adult ...

When attempting to use a value outside of its block, the function may return a

My current task involves querying one collection to retrieve IDs, then using those IDs to query another collection and send back the response. The process runs smoothly until I encounter an issue with retrieving values outside of a block when using forEach ...