The value returned by a mocked Jest function is ignored, while the implemented function is not invoked

Having an issue with mocking the getToken function within my fetchData method in handler.ts while working with ts-jest. I specifically want to mock the response from getToken to avoid making the axios request when testing the fetchData method. However, despite my efforts, I still see the "called getToken" console log when running the test.

I am aware that moving getToken to a separate file would solve this problem, but I am curious about why it isn't working in this scenario as it may occur frequently in the future.

export const getToken = async (params: {}): Promise<string> => {
  try {
    console.log("called getToken");
    const oauthResponse = await axios.post(`url`, params);
    return oauthResponse.data.token;
  } catch (e) {
    throw new Error("Exception caught getting token");
  }
};

export const fetchData = async (params: {}): Promise<any> => {
  try {
    console.log("called fetchData");
    const tokenValue = await getToken(params);
    const response = await axios.post(`url`, params, {
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + tokenValue,
      },
    });
    return response.data.body;
  } catch (e) {
    throw new Error("Exception caught");
  }
};

This is how my handler.test.ts file looks like:

import { fetchData, getToken } from "./handler";

...

  (getToken as jest.Mock).mockResolvedValue(mockedTokenValue);
  (axios.post as jest.Mock).mockResolvedValue(response);

  const result = await fetchData(params);

...

I've also attempted the following:

jest.mock(".handler", () => ({
  ...jest.requireActual("./handler"),
  getSFEToken: jest.fn().mockImplementation(() => {
    return "mocked_token";
  })
}));

Here are snippets of my jest.config.ts and tsconfig.json for reference:


import type { Config } from "jest";

const config: Config = {
  preset: "ts-jest",
  testEnvironment: "node",
};

export default config;

{
  "compilerOptions": {
    "esModuleInterop": true,
    "module": "commonjs",
    "target": "es5",
    "sourceRoot": "src",
    "outDir": "dist",
    "noImplicitAny": false,
    ...
  ],
  ...
  }
}

Ps. I have referred to https://jestjs.io/docs/bypassing-module-mocks for guidance. Despite trying various mocking techniques and spies, the actual implementation of getToken is being called instead of the mocked value.

Answer №1

If you want to easily test something, one approach is to inject its external dependencies. Mocking the module globally is an option, but keep in mind that if your test function and the mocked function are within the same module (file), they will both be mocked.

For axios testing, make sure to import axios and use jest.mock('axios') in the test file.

In a specific scenario, you can modify fetchData to optionally accept getTokenFunction.

Here’s an example:


export const getToken = async (params: {}): Promise<string> {
  //....
}

export const fetchData = async (params: {}, getTokenFunction = getToken): Promise<any> {
  //real implementation
}

// Test file
import { fetchData } from "./handler";
import axios from "axios"

// Mock axios globally
jest.mock('axios');

// Necessary for response manipulation in each test
const mockedAxios = axios as jest.Mocked<typeof axios>;

describe("Description of the test", () => {
  beforeEach(() => {
    // Reset all mocks before each test
    jest.resetAllMocks();
  });

  it("Test description", async () => {
    // Setup
    const mockedResponse = {};
    mockedAxios.post.mockResolvedValue(mockedResponse);
    const getTokenMock = jest.fn().mockResolvedValue("desired result");

    // Action
    await fetchData({}, getTokenMock);

    expect(getTokenMock).toHaveBeenCalledWith(mockedResponse);
  });
})

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

How can we programmatically trigger a click action on an element obtained through an HTTP request with the help of Set

window.addEventListener("load" , () => { setInterval(() => { let xhttp = new XMLHttpRequest(); xhttp.open("GET", "./messagedUsers.php", true); xhttp.onload = () => { if(xhttp.re ...

The functionality of the button is disabled once a pop-up JavaScript is implemented

I have encountered an issue with my HTML code that involves a button intended to hide certain content. The problem arose when I implemented a popup feature, causing the button to malfunction. Here is the JavaScript for the popup: $ = function(id) { retur ...

Caution: It is not possible to make updates on a component while inside the function body of another component, specifically in TouchableOpacity

I encountered this issue: Warning: Trying to update a component from within the function body of another component. Any suggestions on how to resolve this? Interestingly, the error disappears when I remove the touchable opacity element. ...

Is it possible to eliminate auxiliary routes in Angular 4?

Recently, I came across an interesting scenario with two <router-outlet> tags, one with a name property. To test this, I set up the following router mapping: export const routing = [ {path:'', pathMatch:'full', component:E ...

Having trouble importing zone.js in Angular 14 and Jest 28

I am currently in the process of updating to Angular 14. Everything is going smoothly except for setting up jest. Since I have Angular 14 libraries included in my build, I need to utilize jest-ESM support. Below is my configuration: package.json { &qu ...

MongoDB date query with $gte and $le operators mm/dd/yy

Apologies in advance for any language errors. The problem I am dealing with involves a column in the database called "Date" inside the "startOn" Object. This setup creates a structure like "startOn.Date" with data format as yyyy/dd/mm. For example, if we ...

jQuery import children into output

When inserting a div every nth-child and later calling the children of the parent, the jQuery inserted elements do not appear in this new list. How can I retrieve the inserted elements as well? Apologies if this is confusing. If it's easier to under ...

What makes Mathematics a unique object in JavaScript programming?

Recently, I've dived into learning Javascript, so pardon me if my doubts seem a bit illogical. I came across the definition for a Math object, and here is the code snippet: interface Math { /** The mathematical constant e. This is Euler's nu ...

When I use AJAX to load a PHP file, the function's content returns as [object HTMLDivElement]

Hello there, When I use AJAX to load a PHP file, the content of my function returns [object HTMLDivElement], but if I load my function without loading the PHP file, it displays normally. index.php <h1>API Football</h1> <nav> ...

The defineProps<SomePropType>() method is not rendering the props as expected

I have various components, with a parent element where I attempted to pass props using the syntax defineProps<{}>(). The setup is simple, I have a types.ts file at the root level, a parent Vue file (referred to as CardItem), and multiple components. ...

What is the best way to remove an active item from a Vue v-list?

When using Vuetify's v-list-item directive, I encountered an issue where the active prop cannot be removed once an item has been selected. Here is my approach so far: <v-list-item-group pb-6 color="primary" class="pb-3 text-left"> ...

Element remains hidden until the developer console is activated

On my website, I've noticed that certain LayerSlider elements are remaining invisible until: The window is resized I disable the Bookmarks bar in Chrome (quite strange, right?) I switch on the Chrome debugger tools This issue is not exclusive to Ch ...

Canvas drawImage function not displaying image at specified dimensions

I'm having trouble loading an image into a canvas using the drawImage function. Additionally, I've implemented drag functionality but found that when moving the image inside the canvas, it doesn't follow the mouse cursor in a linear manner. ...

Files with extensions containing wildcards will trigger a 404 error when accessed from the public folder in NextJS

I have successfully set up my public folder to serve static files, however I am encountering an issue with files that have a leading dot in their filename (.**). Specifically, I need to host the "well-known" text file for apple-pay domain verification, wh ...

Selective Circle Appending Techniques

I am having some issues with my bubble chart code. The data file I am working with contains instances where the GDPperCapita and/or LifeExpectancy values are either 0 or NaN, causing problems when appending circles to the chart. I would like to know if th ...

What are effective solutions to reduce the increasing Next.js bundle size caused by dynamic component lookup?

tldr: For more information, please visit the repository. The common.js file includes all dependencies, even though only one is used on the current page. http://localhost:3000/components/ComponentOne http://localhost:3000/components/ComponentTwo Live dem ...

AngularJS : "Executing successive promises" with additional functions interspersed

Recently, I encountered a challenge in my Angular project. As a newcomer to Angular, I was tasked with modifying a directive that handles forms to ensure the submit button is disabled during processing and then enabled again once all operations are complet ...

Using V-model in conjunction with the boostrap-vue b-table component

I am attempting to bind v-model by passing the value inside the items array. However, the binding is not functioning correctly. The main objective here is to utilize a store since all these values are utilized across multiple "wizard" components. Whe ...

Collections of both letters and non-letter characters that are aligned

I am attempting to identify sets of characters that contain a mix of letters and non-letter characters, with many of them being just one or two letters. const match = 'tɕ\'i mɑ mɑ ku ʂ ɪɛ'.match(/\b(p|p\'|m|f|t|t ...

Having trouble with script tag not loading content in Next.js, even though it works perfectly fine in React

Currently, I am attempting to utilize a widget that I have developed in ReactJS by utilizing script tags as shown below- React Implementation import React from "react"; import { Helmet } from "react-helmet"; const Dust = () => { ...