How can you verify the anticipated log output in the midst of a function execution with Jest unit testing?

Below is a demonstration function I have:

export async function myHandler(
    param1: string,
    param2: string,
    req: Request,
    next: NextFunction,

) {
    const log = req.log.prefix(`[my=prefix]`);
    let res;
    If (param1 === 'param1') {
        log("GOT PARAM 1");
    } else {
        res = await doSomething();
    }
    log("GOT HERE");
    ..
    ..
    ..
    ..
    res.setReturnStatus(200)
    }
    next();
}

As for the logger, this is the structure of the request containing it:

 const req: {
url: string;
params: {};
body: {
    device: {
        type: string;
        p1: string;
        p2: string;
        p3: string;
    };
    data: {
        sample: number;
    };
};
metric: () => jest.Mock<any, any>;
log: {
    (): jest.Mock<any, any>;
    warn(): jest.Mock<...>;
    error(): jest.Mock<...>;
    prefix(): jest.Mock<...>;
};
timing: () => jest.Mock<...>;

}

When writing my unit test, I am checking the return status with this line:

expect(res.status).toBeCalledWith(200);

I aim to cover the first 'if' statement, which logs 'GOT PARAM 1', but struggling to intercept the call in the middle.

doSomething = jest.fn(() => Promise.resolve());
await myHandler('param1', 'param1', next); //HERE to somehow verify that was also logged?
expect(res.status).toBeCalledWith(200);

I attempted something like :

const spy = jest.spyOn(req.log, 'log');

resulting in an error:

Cannot spy the log property because it is not a function; undefined given instead

Answer №1

When using the log function that comes from the req, make sure to pass the mocked implementation through it:

let mockLog = jest.fn();
let mockReq = { log: { prefix: jest.fn().mockReturnValue(mockLog) } };
await myHandler('param1', 'param2', mockReq, next);
expect(mockReq.log.prefix).toBeCalledWith(...);
expect(mockLog).toBeCalledWith(...);

There was an issue with the attempt because it should be req.log.prefix instead of req.log.log:

const spy = jest.spyOn(req.log, 'log');

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

Combining multiple Float32Arrays to create a single Float32Array

I need help creating a function that can flatten multiple Float32Arrays into one large Float32Array const first = new Float32Array([1,2]); const second = new Float32Array([3,4,5]); const third = new Float32Array([6,7,8,9]); const chunks = [ ...

Cypress and Cucumber collaborate to reinitialize the requests within Next Js

In my upcoming project with Next.js, I am utilizing Cypress for testing a specific page. The objective is to validate two scenarios: 1. Successful outcome and 2. Error handling when a user encounters an issue. Before(() => { return void cy.server() ...

What is the best way to create a TypeScript interface or type definition for my constant variable?

I'm facing challenges in defining an interface or type for my dataset, and encountering some errors. Here is the incorrect interfaces and code that I'm using: interface IVehicle { [key: number]: { model: string, year: number }; } interface IV ...

Unable to change data in table TD using AJAX and PHP received JSON array

I am currently facing an issue with a PHP-AJAX script that is responsible for deleting financial rows from a table. The PHP script is functioning correctly and successfully deleting the rows. However, the problem arises within the success function of the A ...

Tips for creating a smooth transition effect using CSS/JavaScript pop-ups?

Looking for some assistance in creating a CSS pop-up with a touch of JavaScript magic. I've managed to trigger the pop-up box by clicking a link, and while it's visible, the background fades to grey. But I'm struggling to make the pop-up fad ...

Best method for distributing components across nextjs zones?

Scenario: I am currently working on a project using Next.js and taking advantage of its multi zones feature. This feature allows us to run multiple independent NextJS applications as a unified app, managed by different teams. The Issue: One challenge I fa ...

React Query successfully retrieves the path, but unfortunately fails to render the image in the display

Currently facing an issue where I am trying to retrieve images from the backend using ReactQuery. Here is the ReactQuery code snippet: export const useGetProductImagesByProductId = (productId: string) => useQuery({ queryKey: ['productIm ...

The domain name or IP address does not correspond to the alternate names listed on the certificate

I am currently facing an issue with installing npm packages in my react native project. Every attempt to install a package from npm results in the error message shown below: fitz:tesseractOcrSample fitzmode$ npm i npm ERR! request to https://registry.npmj ...

"Material-UI enhanced React date picker for a modern and user-friendly

Currently, I am utilizing the Date picker feature from Material UI. The code snippet responsible for implementing it is as follows: import { DatePicker } from 'redux-form-material-ui'; <Field name="birthDate" ...

Ways to modify the CSS of an active class within a child component when clicking on another shared component in angular

In my HTML template, I am encountering an issue with two common components. When I click on the app-header link, its active class is applied. However, when I proceed to click on the side navbar's link, its active class also gets applied. I want to en ...

The bootstrap datepicker does not display the date range on the calendar

I tried to incorporate a bootstrap datepicker date-range in the code snippet below, but I am encountering an issue where the selected date range is not displaying on the calendar. <!DOCTYPE html> <html> <head> <link rel="stylesheet" ...

Determine the width of the window and adjust the positioning of jQuery UI tooltips accordingly

Struggling to adjust the jQuery UI tooltip position based on screen width, but can't seem to figure it out. Can someone assist me in detecting the browser's width and changing the tooltip position accordingly? [fiddle] $(function () { $(doc ...

I have an HTML table with multiple cells containing inner HTML tables. I have implemented a function along with buttons to filter the main table, excluding the inner tables

My HTML Table is generated from my database, containing information about machines and their status pulled from emails with HTML Tables. Each row has a click option to open/hide the <td> tag showing the original table for more details and better trac ...

Guide to ensuring modal box only appears once all criteria are satisfied

On my website, I have a form that requests the user's personal information. After filling out the form, a modal pops up with a "Thank you for signing up" message. The issue is that even if all fields are left blank and the button is clicked, the modal ...

Ways to determine the total number of npm packages installed, excluding development dependencies

Is there a specific NPM command I can run from the CLI to count only the installed NPM Modules in my package that are not Dev Dependencies? When I use npm ls, it lists all packages without distinguishing between regular dependencies and DevDependencies. ...

Guide on integrating external libraries with Angular CLI

I've been working on incorporating external libraries into my project, and I've been following the instructions provided here. While I know it's possible to use CDNs in my index.html, I'm interested in learning how to do it using TypeS ...

PHP is capable of showing echo statements from the function, however it does not directly showcase database information

My current challenge involves using AJAX to pass the ID name of a div as a string in a database query. Despite being able to display a basic text echo from my function, I'm unable to retrieve any content related to the database. // head HTML (AJAX) $( ...

Retrieving a pair of data points from a Vue <select> event when it changes

I am facing an issue with a dropdown menu that is using an array with key:value pairs. I want the dropdown to only show values, but when a selection is made, I need to pass both the value and the key using the @change event. <select @change=" ...

Tips on running jQuery scripts when a div changes its display style from none to block?

Is there a way to trigger jQuery code when the style of a div transitions from `display: none;` to `display: block;`? I am working with tabs, which is why this div's style changes in this manner. The jQuery code should only be executed when this spec ...

Multi-Slide AngularJS Carousel

My current setup includes a carousel like so: <div> <carousel id="myC" interval="3000" > <slide ng-repeat="order in orders"> <img ng-src="whatever.jpg" style="margin:auto;"> <div ...