Strategies for evaluating a Promise-returning imported function in Jest

I am currently facing an issue with a simple function that I need to write a test for in order to meet the coverage threshold.

import { lambdaPromise } from '@helpers';

export const main = async event => lambdaPromise(event, findUsers);

The lambdaPromise() function is supposed to return a Promise. My goal is to mock this function and determine if it was called. Here is my current code:

import { main, findUsers } from '../src/lambdas/user/findUsers';
import { lambdaPromise } from '@helpers';

const mockEvent = {
  arguments: {
    userDataQuery: {
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfa5a0a7a1aba0aa8fb8a7aebbaab9aabde1aca0a2">[email protected]</a>'
    }
  }
};

const mockLambdaPromise = jest.fn();

jest.mock('@helpers', () => ({
  lambdaPromise: jest.fn().mockImplementation(() => mockLambdaPromise)
}));

describe('findUsers', () => {
  it('should have a main function', async () => {
    const mockPromise = main(mockEvent);
    expect(mockPromise).toBeInstanceOf(Promise);
    expect(mockLambdaPromise).toBeCalledWith(mockEvent, findUsers);
  });
});

However, the mockLambdaPromise function never gets called. How can I resolve this issue?

Answer №1

Ensure to call the function returned by your mock in order for it to pass successfully. Here's how:

jest.mock("./helpers", () => ({
  lambdaPromise: jest
    .fn()
    .mockImplementation((a, b) => mockLambdaPromise(a, b)),
}));

To simplify the complexity of the mock, consider only mocking the resolved value with a spy like this:

import { main, findUsers } from "./findUsers";
import * as helpers from "./helpers";

describe("findUsers", () => {
  it("should have a main function", async () => {
    const spy = jest.spyOn(helpers, "lambdaPromise").mockResolvedValue();
    await main(mockEvent);
    expect(spy).toBeCalledWith(mockEvent, findUsers);
  });
});

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

What is the best way to evaluate typing into an input field?

My objective is to test the 'typing' functionality in an input element. The aim is to insert a value into the input element, verify that its binding successfully captures the value, and observe the entered value within the input element. Below i ...

Guide on displaying a tooltip for an object in an Angular component using Bootstrap syntax

i have a data object structured like this var obj = {"test price type ty dynamic ": 10, test: 7, pricetype1u: 0, Price type 3: 0, Price type 2: 0} in my Angular component HTML, with Bootstrap styles applied, I've written the following code ...

Bringing an AMD module into a Mocha test

I recently encountered an error while using Mocha to test code that was exported as an AMD module. When running the Mocha test, I received the following error message: ReferenceError: define is not defined at Object.<anonymous> (/home/malintha/proje ...

An intuitive approach to adding a CheckBox control within a GridView using JavaScript and SPAN elements

Struggling to calculate the total quantity from the gridview for checked row checkboxes? Having trouble accessing the checkbox control in your JavaScript? Below is the code snippet you provided, but it's not returning anything. <table cellspaci ...

Leveraging props in React to retrieve information from MongoDB and incorporate it into a component

I am currently working on a project where I need to fetch data from mongodb in order to display a list of products on my homepage. I am using react with 3 components - Home.tsx, PizzaList.tsx, and PizzaCard.tsx. The usestate hook and useEffect hook are bei ...

What approach can be taken to establish a dependency between an AngularJS controller and a value that is retrieved through ajax and loaded onto the root

I have an app that loads like this: app.js file: angular.module('App', []).run(['$rootScope', '$q', 'SessionManager', 'EndpointService', function ($rootScope, $q, SessionManager, EndpointService) { $r ...

What is the reason behind receiving the error message "Unable to resolve all parameters for ApplicationModule"?

I am experiencing an issue with my Angular app as it is not working properly in CodeSandbox. The error message I receive is: Can't resolve all parameters for ApplicationModule evaluate main.ts:11:25 8 | enableProdMode(); 9 | } 1 ...

Transfer the script from package.json to an npm package

In each of our plugins' root directories, there is a file named tools.js. This file contains a build function that assists in creating builds for the plugin. The package.json file references it like this: "scripts": { "build:node&qu ...

Creating a Stroke on an html5 canvas with the help of EaselJS

As a newcomer to Easel and HTML5, I am attempting to draw a line on a canvas using EaselJS. The X-coordinate is set to 100 while the Y-coordinate is taken from an array list. Below is the code I have written. Can someone please help me identify where my ...

Opacity effect on input text when it exceeds the input boundaries

I'm having an issue: I need to create inputs with different states, including when the text is longer than the input itself. In this case, the extra text should fade out with a gradient transparency effect: https://i.sstatic.net/r5qQu.jpg Here is my ...

Having trouble with Vue image source file paths?

Having an issue with loading an image via file_path on Vue. When using a hardcoded path, it works fine. Refer to the sample code below: JavaScript function getRestaurantsbyId(id) { var restaurants = { "1" : { "name": "xxxx", ...

Having trouble getting my AngularJS directive with a number in the name to function properly

Check out my code snippet: app.directive('3dPlansSlider', function(){ return { controller: 'projectCtrl', restrict: 'E', templateUrl: 'views/3dPlansSlider.html', link: function(scope, element, attr ...

Material Angular table fails to sort columns with object values

Currently, I am in the process of developing a web application using Angular Material. One of the challenges I have encountered is displaying a table with sorting functionality. While sorting works perfectly fine on all columns except one specific column. ...

enzyme unable to mount component for the second time

Currently, I am conducting tests on a redux-connected component. The component in question utilizes useSelector, so I have implemented some guidance from this particular answer to simulate the response from useSelector, which is performing admirably well. ...

Edit esri pop-up template

Can I customize the popupTemplate in Esri to match my design? I currently have a popupTemplate set up like this: popupTemplate: { content: [{ type: "fields", fieldInfos: [{ fieldName: "Name" ...

Enhance the progression bar using JavaScript

Is there a way to dynamically update a progress bar in HTML while a function is running? function fillProgressBar() { var totalIterations = 100; for (var i = 1; i <= totalIterations; i++) { //perform calculations progressBarWidth = (i/to ...

Merge two JSON objects together by matching their keys and maintaining the original values

After having two separate JSON objects representing data, I found myself in the position of needing to merge them into one combined result. The initial objects were as follows: passObject = { 'Topic One' : 4, 'Topic Two' : 10, &apos ...

The error message states: `res.Send function is not recognized as a valid

Recently, I've been working on a function that goes like this: app.get('/counter', function (req, res) { console.log('/counter Request'); var counter = 0; fs.readFile(COUNTER_FILE_NAME, function(err, data) { c ...

Closing the Angularstrap dropdown when clicking elsewhere

Is there a method to close an angularstrap dropdown only when clicking outside of it? The current behavior is that it closes when you click inside the dropdown. Thank you ...

Deployment failure of AWS CDK caused by Error: Lambda Function Invalid

I'm in the process of integrating a Lambda authorizer into my REST API using AWS CDK. const api = new apigw.RestApi(this, 'apiname', { defaultCorsPreflightOptions: { allowOrigins: apigw.Cors.ALL_ORIGINS } }); const authorizerFuncti ...