Observer function simulated by SinonStub

I am currently testing express middleware using sinon.js

My goal is to verify that it sends a specific JSON response and prevents the request from moving on to the next middleware or request handler.

const middleware = (req: Request, res: Response, next: NextFunction) => {
  setTimeout(() => res.json({status: 'blocked'}), 1000);
}

To mock the Request and Response objects, I am utilizing sinon-express-mock. This allows me to have every property and method in the Response object as a SinonStub.

The issue I am encountering is that when I invoke the middleware and the json method is triggered, I am unsure how to check it afterwards.

Is there a listener or observer available for SinonStub?

Thank you.

Answer №1

Below is the solution for the unit test:

index.ts:

import { NextFunction, Response, Request } from 'express';

const middleware = (req: Request, res: Response, next: NextFunction) => {
  setTimeout(() => res.json({ status: 'blocked' }), 1000);
};

export { middleware };

index.test.ts:

import { middleware } from './';
import { Request } from 'express';
import sinon, { SinonFakeTimers } from 'sinon';

describe('56676480', () => {
  let clock: SinonFakeTimers;
  before(() => {
    clock = sinon.useFakeTimers();
  });
  after(() => {
    clock.restore();
  });
  it('Test should be successful', () => {
    const mReq = {} as Request;
    const mRes = { json: sinon.stub() } as any;
    const mNext = sinon.stub();
    middleware(mReq, mRes, mNext);
    clock.tick(1000);
    sinon.assert.calledWithExactly(mRes.json, { status: 'blocked' });
  });
});

Results of the unit test with 100% coverage:

  56676480
    ✓ Test should be successful


  1 passing (12ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.ts |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------

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 origin of the libraries found in npm-shrinkwrap that do not match the packages listed in package.json?

I'm puzzled by the presence of `express` in my `npm-shrinkwrap` file as a main dependency. Despite this, `express` is not listed as a dependency in my `package.json` file. I can't find any usage of it in my project. It's not included a ...

Is it possible to manipulate the response from a MySQL server using Node.js?

For example: The following response represents the original data { "todo_id": 2, "todo_item": "brush your teeth", "scheduled_time": "2020-03-22T07:14:29.000Z", "user_id": 1, "is_done": { "type": "Buffer" ...

Implementing a smooth camera movement in Three.js using the mousewheel

Is there anyone who can assist me with achieving smooth camera movement (forward/backward) using the mouse wheel? The current code I have is not providing the desired smoothness. document.addEventListener( 'mousewheel', onDocumentMouseWheel, fal ...

How to effectively handle null values using try..catch statement in typescript

As a beginner, I am learning how to write a try/catch statement in TypeScript. My issue is that there is a function within the "try" block that returns null. How can I implement code in the "catch" block specifically for when the function in "try" returns ...

Show the error message from passport.js authentication in the user interface

I am currently working on a new project with Sails.js and using Passport.js for user authentication. Despite having the basic authentication set up, I am struggling to display error messages in the login view when incorrect credentials are entered. I have ...

It is not possible to include parameters in mongoose schema that have not been defined

Is it possible to add new parameters in a MongoDB collection that are not defined in the Mongoose schema? Below is the current schema: var mongoose = require('mongoose'); var Schema = mongoose.Schema; var UsersSchema = new Schema({ FirstNam ...

Can we set a specific length for an array passed in as a prop?

Can we use Typescript to specify the exact length of an array coming from props? Consider the following array of objects: const sampleArray = [ { key: '1', label: 'Label 1', value: 9 }, { key: '2', label: 'Label 2&ap ...

Implementing a click event on header elements within a full calendar component in a React application

I'm currently integrating full calendar into my project. I need to implement click events on the header buttons such as prev, next, today, and others. This is how I've set up full calendar with the specified header buttons: <FullCalendar d ...

The property this.props.Values is not defined

I'm facing an issue with a page. Specifically, I am working with the value: this.props.CategoriesList. This value represents a list of categories. The problem is that when I click on a button to navigate to the page where this value is used, it shows ...

Issue encountered: Next.js has failed to hydrate properly due to a discrepancy between the initial UI and server-rendered content

Uncertain about the cause of this error? The error seems to disappear when I remove the provided code segment. What is triggering this error in the code snippet and how can it be fixed? <div className="relative flex flex-col items-center pt-[85.2 ...

Using Express-session in the Internet Explorer browser

When configuring the express-session plugin, I follow this setup: var express = require('express'), session = require('express-session'), uuid = require('node-uuid'); var expiration_day = new Date('9/15/2015&apo ...

Error encountered: NextJs could not find the specified module, which includes Typescript and SCSS

I am in the process of migrating a Next.js application from .js to .ts and incorporating ScSS. The first error I encounter is during 'npm run dev'. However, when I try 'npm run build', different issues arise that do not seem related to ...

Slowly revealing sticky navigation with slideDown animation using JQuery

Here is the code for a .JS file: $(document).scroll(function (){ var menuheight= $('header').height(); var y = $(this).scrollTop(); if (y>(menuheight)) { $('.menu_nav_features').addClass ...

Validating forms in ReactJS

I have developed a basic form validation feature for React. The inspiration for this project came from the following source: When I try to submit the form, input errors arise within the isValid function. I am seeking assistance in resolving this issue. A ...

Scrolling in iOS 8 causing flickering problem with background image

Utilizing the Supersized jQuery slider plugin to create a full-page background slider with a fade-in effect and added height for scrolling. The slider functions correctly on desktop, but upon testing on an iOS 8 iPad device, there is noticeable flickering ...

Getting undefined while trying to iterate through data on a next js page using getStaticProps. What could be causing this issue?

Encountering difficulties while trying to output the page meta data in next.js when I execute: npm run build An error is thrown with the following message: Error occurred prerendering page "/blog/[...slug]". Read more: https://err.sh/next.js/pre ...

To access an express server, use port 3000, while port 8081 is designated for react native. Learn how to send

I am currently developing an Avatar Builder app using React Native that I plan to deploy on both iOS and Android platforms. My server is running on Express, which uses localhost:3000, while React Native runs on localhost:8081. import axios from 'axio ...

Importing BrowserAnimationsModule in the core module may lead to dysfunctional behavior

When restructuring a larger app, I divided it into modules such as feature modules, core module, and shared module. Utilizing Angular Material required me to import BrowserAnimationsModule, which I initially placed in the Shared Module. Everything function ...

Attempting to utilize the async/await method to retrieve a service, but unfortunately, the returned values from the second service are not populating my variables as intended

I am having an issue with my service where I retrieve a list from the server. The problem is that within this list, I need to make another service call to fetch logo images. Although the service call returns successfully, my list still remains empty. Can y ...

Issue with React hook forms and shadcn/ui element's forwardRef functionality

Greetings! I am currently in the process of creating a form using react-hook-form along with the help of shadcn combobox. In this setup, there are two essential files that play crucial roles. category-form.tsx combobox.tsx (This file is utilized within ...