Testing API route handlers function in Next.js with Jest

Here is a health check function that I am working with:

export default function handler(req, res) {
  res.status(200).json({ message: "Hello from Next.js!" });
}

Alongside this function, there is a test in place:

import handler from "./healthcheck"

describe("Healthcheck", () => {
  test("verifying the application is live and returning status 200", () => {
    const mockFn = jest.fn({
      status: jest.fn(),
      json: jest.fn()
    });

    expect(mockFn).toHaveBeenCalledWith();
    expect(mockFn.status).toBe(200);
  });
});

While testing, the main goal is to ensure that the function is being executed and the response status is set to 200. To achieve this, it is necessary to properly mock out the functions within the request and response objects.

Answer №1

In the function handler, there is a parameter called res that can be mocked and passed into the function when testing. By doing this, you are able to verify that the mocks were called correctly.

import handler from "./healthcheck"

describe("Healthcheck", () => {
    test("Ensuring the application is running with a status of 200", () => {
        const resMock = { status: jest.fn() }; // Creating a mock for `res`
        const resStatusMock = { json: jest.fn() }; // Mocking `res.status`
        resMock.status.mockReturnValue(resStatusMock); // Setting `res.status` return value as `resStatusMock`
        
        handler(undefined, resMock);

        expect(resMock.status).toHaveBeenCalledWith(200);
        expect(resStatusMock.json).toHaveBeenCalledWith({
            message: "Hello from Next.js!"
        });
    });
});

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

Tips for ensuring that a nested object in an array contains only a single object

My array is structured like this: [ { object1:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object2:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object3:{ childObj1:[grandChild1,grandChild2 ...

Efficiently managing multiple database updates with PHP and JQuery

Having trouble processing multiple mySQL updates simultaneously? I have 4 select/option boxes fetching data from a db table and I want to update the database onChange using JQuery. It's working with one select module, but adding more causes issues. Th ...

Activate the Air-mode feature in Summernote in addition to the standard toolbar

Is it possible to have both the default toolbar and air-mode toolbar enabled in the Summernote editor? For instance, I would like the user to utilize the default toolbar for general text editing, but have the air-mode toolbar appear when they select a spe ...

Refresh Chart Information using Ng2-Charts in Charts.js

Utilizing chart.js and ng2-charts, I am developing gauge charts for my platform to monitor the fluid levels inside a machine's tank. The values are retrieved from an external API, but I am encountering an issue where the charts are rendered before I ...

How can one correctly import node modules in the handler function of next.js API?

I need to import bcrypt in a file located in my /api directory. // pages/api/login.js const bcrypt = require('bcrypt'); export default async function handler(req, res) { switch (req.method) { case 'POST': // do stuff with b ...

Is it possible to use the .focus() event on an entire form in JQuery? If so, how

Take a look at this HTML snippet: <form ....> <textarea>....</textarea <input .... /> </form> I'm trying to set up a help section that appears when the user focuses on any form element, and disappears when they lose ...

`Is there a way to modify the attribute text of a JSON in jQuery?`

I'm attempting to modify the property name / attribute name of my JSON object. I attempted it like this but nothing seems to change. After reviewing the input JSON, I need to convert it to look like the output JSON below. function adjustData(data){ ...

"An undefined message will be displayed in AngularJS if there is no content

When the two textboxes are left empty, you will see errors as 'undefined' displayed. These errors disappear once content is entered. The code I have written looks like this: Default.aspx <div ng-app="Welcomecontroller" ng-controller="FullNa ...

Image not showing up when using drawImage() from canvas rendering context 2D

Need help with drawImage() method in JavaScript <head> </head> <body> <script type = "text/javascript"> var body, canvas, img, cxt; body = document.getElementsByTagName("body" ...

Tips for utilizing node.io for HTML parsing with node.js?

Struggling to utilize node.io with node.js for parsing an HTML page stored as a string in a variable. Encountering difficulties passing the HTML string as an argument to my node.io job. Snippet from my node file nodeiotest.js: var nodeIOJob = requi ...

Add the file to the current directory

As a newer Angular developer, I am embarking on the task of creating a web page that enables users to upload files, with the intention of storing them in a specific folder within the working directory. The current location of the upload page component is ...

I am having trouble getting Google Maps to load

Why does the map on my website only load when the browser window is resized? Below is the JavaScript code being used: <div class="map-cont"> <div id="map" class="location-container map-padding" style="width:100%;height:400px;background:y ...

Transform the Material UI grid orientation to horizontal row for content display

I'm just starting out with material UI and I've put together a grid that includes two components - an autocomplete and a button. Right now, they're stacked on top of each other, but I want to align them side by side in a row. Here's the ...

Transferring String data between Java and JavaScript using Webview in both directions

I'm currently developing an application that allows two users to communicate via a webview. My goal is to transfer a String variable from JavaScript to Java in order to store it in my SQLite database, and also be able to do the reverse operation as we ...

Utilizing Jquery to interchange two values and update styling

I am looking to create a script that allows me to select a black div by clicking on it (turning it red), and then transfer the value from the black div into a white div with another click. The functionality works as expected when swapping values between tw ...

Removing a pin from google maps using a personalized delete button

I have encountered an issue while attempting to remove a marker from Google Maps using a custom delete button within the info window. Even though I have successfully added the button and necessary information, it seems that the function responsible for del ...

Mocking a service dependency in Angular using Jest and Spectator during testing of a different

I am currently using: Angular CLI: 10.2.3 Node: 12.22.1 Everything is working fine with the project build and execution. I am now focusing on adding tests using Jest and Spectator. Specifically, I'm attempting to test a basic service where I can mo ...

Finding the file path to a module in a NextJS application has proven to be a challenge when utilizing the module

Currently, I am utilizing the webpack plugin module-federation/nextjs-mf, which enables us to work with a micro-frontend architecture. Based on the official documentation and referencing this particular example, it is possible to share components between ...

Is Jquery getting imported correctly, but AJAX is failing to work?

I am currently working on a Chrome extension that automatically logs in to the wifi network. I have implemented AJAX for the post request, but when I inspect the network activity of the popup, I do not see any POST requests being sent. Instead, it only sho ...

Ways to display pictures by invoking an API within the antd item list container

Upon page load, I am fetching images from a database using an API. Now, my goal is to display these images within a Modal in Antd. How can I accomplish this with the code snippet below? const MyVehiclePage = (props) => { useEffect(() => { co ...