Using jest in typescript to simulate HttpRequest body and InvocationContext in @azure/functions

I have the following function and I am trying to write a test for it, but I'm having trouble figuring out how to mock HttpRequest

import { app, HttpRequest, HttpResponseInit, InvocationContext } from "@azure/functions";
export async function create(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {  
  context.log(`addFeedback processing request for url "${request.url}, ${context.invocationId}"`);
  // get product list from cosmosdb 
  return {
    status: 200,
    jsonBody: {
      product,
    },
  };

Does anyone know how to properly mock InvocationContext and HttpRequest in TypeScript for testing purposes?

Answer №1

If you want to utilize Jest for mocking your Azure Functions' Javascript HttpTrigger, you can refer to my detailed explanation on Stack Overflow: SO Answer

To install the necessary Jest dependencies:-

npm install @azure/functions jest supertest --save-dev

Sample Azure Function HttpTrigger code snippet:-

const { app } = require('@azure/functions');

app.http('httpTrigger1', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    handler: async (request, context) => {
        context.log(`Http function processed request for url "${request.url}"`);

        const name = request.query.get('name') || await request.text() || 'world';

        return { body: `Hello, ${name}!` };
    }
});

Example test file: index.test.js

const request = require('supertest');
const { app } = require('@azure/functions');

describe('Azure Function Tests', () => {
    it('should respond with "Hello, world!" for GET request without name parameter', async () => {
        const response = await request(app)
            .get('/api/httpTrigger1')
            .expect(200);
        expect(response.text).toBe('Hello, world!');
    });

    it('should respond with "Hello, John!" for GET request with name parameter', async () => {
        const response = await request(app)
            .get('/api/httpTrigger1')
            .query({ name: 'John' })
            .expect(200);
        expect(response.text).toBe('Hello, John!');
    });

    // Add more test cases as needed
});

Expected Output after running tests:-

Execute npx jest command:-

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

"Animating a card to slide in from the left side upon clicking a button in a React app

How can we create a feature where, upon clicking "Apply Coupon" in Image 1, a window slides in from the left just above the webpage (as shown in Image 2)? Additionally, in Image 2, there is a blue transparent color on the webpage adjacent to this sliding w ...

Unable to get jQuery waypoints to function on local server

Currently, I am working with jQuery. I downloaded an example shortcut for infinite scroll from jQuery Waypoints and tried to use it. However, when the page reaches the end, the web console displays the following error: XMLHttpRequest cannot load file:// ...

There seems to be an issue with posting JSON data correctly

Currently, I am attempting to include an object with numerous attributes within it. This is the object I am trying to use with $.post: ({"fname" : fname, "lname" : lname, "gender" : gender, "traits" : { "iq" : inte ...

In Node.js, JavaScript, when using SQLite, the variables are inserted as Null

I have spent a lot of time searching and trying various methods, but I am still unable to solve this issue. My goal is to insert 8 variables received from an API call into an SQLite table. Although the execution seems correct, when I query the table, all v ...

Updating Error: Unable to establish connection with IP address 104.16.21.35 on port 80; Error code: ECONNREFUSED. This issue is being handled by the _

I need help updating my Angular version from 5 to 6 and I'm following these steps: Want to upgrade project from Angular v5 to Angular v6 After running the commands ng update @angular/cli and ng update @angular/core, I encountered the err ...

Changing a class using JavaScript: Adding and removing class dynamics

Currently, I am attempting to create a function that will toggle the visibility of a visual object on and off whenever the user clicks on it. Additionally, I need to implement a click event listener within the HTML class named btn-sauce. Unfortunately, my ...

How can JavaScript be properly embedded using PhantomJS?

My objective is to insert the following code snippet into a website using PhantomJS: javascript document.getElementById("pickupZip").value = "90049"; document.getElementById("refreshStoresForZipPop").click(); After attempting this in my inject.js file, I ...

Identify the absence of search results in an Ajax request to the search page before rendering the HTML content

I am attempting to retrieve JSON code from a page using the following PHP function: private function __ajax_admin_search($username = '') { $result = $this->admin_login->Admin_Username_Ajax($username); $count = count($result); for ...

Utilizing props in makeStyles for React styling

I have a component that looks like this: const MyComponent = (props) => { const classes = useStyles(props); return ( <div className={classes.divBackground} backgroundImageLink={props.product?.image} sx={{ position: "r ...

Having trouble with the jQuery function not working as expected? Can't seem to identify any errors in the code?

I'm attempting to capture the essence of moving clouds from this beautiful theme: (I purchased it on themeforest, but it's originally designed for tumblr) Now, I want to incorporate it into my wordpress website here: The code used to be under ...

The nightmare of Parent-Child Inheritance in JQuery/CSS is a constant struggle

Having difficulty implementing specific JQuery effects into a Bootstrap framework due to its extensive CSS causing issues. Created a test file named testjquery.html connected to a stylesheet defining a hidden element and activating the fade in of this ele ...

JavaScript file slicing leads to generating an empty blob

I am currently working on a web-based chunked file uploader. The file is opened using the <input type="file" id="fileSelector" /> element, and the following simplified code snippet is used: $('#fileSelector').on('change', functio ...

Having trouble with the npm package installation for react-circular-progressbar

I encountered an error when trying to install react-circular-progressbar in my React projects. Why is this happening? npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/em ...

Using jQuery to send information to PHP via an AJAX request

When attempting to use jQuery to send form data to a PHP file, nothing happens when the button is pressed. The jQuery code snippet: $(document).ready(function(){ $("#daily_user_but").click(function(){ $('#result').html('<im ...

Striped shadows in React Three Fiber

Currently in the process of developing a basic 3D object viewer website using Next.js and React-Three-Fiber. Everything was running smoothly until I added a DirectionalLight instance and attempted to make all meshes receive shadows. https://i.sstatic.net/ ...

Limit the frequency of rendering JSX elements in React by implementing debouncing techniques

Is there a way to delay the rendering of a jsx element in order to smooth out the animation? I have an expanding panel with content inside, and when the panel is empty, the animation works well. However, if the panel already contains content, the expansion ...

Encountering an issue while attempting to integrate mongoose with vue and receiving an error

Whenever I attempt to import this code, the page throws an error: Uncaught TypeError: Cannot read properties of undefined (reading 'split') import { User } from '@/assets/schemas' export default { name: 'HomeView', mount ...

Instructions on submitting a form containing multiple select lists using the enter key

After researching various threads, I have come across solutions using the JS onkeypress function to trigger actions with input fields. However, in my case, I need to implement this functionality with a form that consists of multiple select lists instead of ...

Easily send maps and directions straight to your mobile device with mapQuest

Currently creating a web application with mapQuest integration. I have two queries: 1) Is there a way to share routes from the web app to my phone? 2) How can I track my phone device and display the route on the web app? Appreciate any assistance. PS: Us ...

Manipulating divs by positioning them at the top, left, right, bottom, and center to occupy the entire visible portion of the page

Many suggest avoiding the use of table layouts and opting for divs and CSS instead, which I am happy to embrace. Please forgive me for asking a basic question. I am looking to create a layout where the center content stretches out to cover the entire visi ...