What could be causing my sinon test to time out instead of throwing an error?

Here is the code snippet being tested:

function timeout(): Promise<NodeJS.Timeout> {
  return new Promise(resolve => setTimeout(resolve, 0));
}

async function router(publish: Publish): Promise<void> => {
  await timeout();
  publish('requestObject');
};

This is my test scenario. When I use the try/catch block below, it fails immediately with the correct error.

it.only('ensures a valid response', (done) => {
    const publish = sinon.stub();

    publish.callsFake((publishResponse) => {
      try {
        expect(publishResponse).to.equal('wrong');
        done();
      } catch (error) {
        done(error);
      }
    });

    router(publish);

    sinon.restore();
});

If I eliminate the try/catch block, the test ends up timing out with this message:

publish.callsFake((publishResponse) => {
  expect(publishResponse).to.equal('wrong');
  done();
});

Error: Timeout of 5000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

It seems that the promise is not resolving because the expect statement is failing. Consequently, it does not reach the done() method. Is there a better way to rewrite this test? Or is using try/catch the most appropriate approach here?

I have reviewed several Stack Overflow answers related to similar issues which suggest ensuring that the code under test does not ignore errors. However, in my code, I do not see any part where errors are ignored.

Answer №1

Instead of utilizing the callback/done structure, I made it simpler by awaiting the code under test and employing an argument expectation (calledWith) rather than having the expectation inside the fake callback.

The reason why this method works instead of the callback approach is still a bit unclear to me.

  it.only('verifies a valid response', async () => {
    const publish = sinon.stub();

    await router(publish);
    expect(publish).to.be.calledWith('wrong');

    sinon.restore();
  });

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

How to Unsubscribe from an Angular 2 Subscription Automatically After a Timeout

I am looking for a way to disregard the response from my API in case it takes too long to fetch. Currently, I am using this.http.get(mysqlUrl).subscribe() to retrieve the response. However, I would like to terminate that subscription if it exceeds a dur ...

Alerts appear immediately upon beginning to type, asking for 8 characters and ensuring both passwords match

Is it possible to notify users that both passwords should match and they need to enter at least 8 characters after typing? There is currently an issue where a notification appears for entering less than 8 characters, but the password reset still proceeds ...

What is the difference between TypeScript's import/as and import/require syntax?

In my coding project involving TypeScript and Express/Node.js, I've come across different import syntax options. The TypeScript Handbook suggests using import express = require('express');, while the typescript.d.ts file shows import * as ex ...

Encountering compilation errors with TypeScript files in Angular 2 while using Visual Studio 2017

Currently, I am in the process of developing an Angular 2 application Here is a snippet of the TypeScript code that I have written: import { Component } from 'angular2/core'; @Component({ selector: 'my-app', template: ' &l ...

Inversify's Http Context consistently remains void of any content

Hello there, I'm in need of assistance with building an API using inversify and inversify-express-utils. Everything seems to be working fine with my controllers and the API so far, except for one issue. When trying to access the httpContext property i ...

An issue has been encountered at the header component of an Angular web application, identified as error code

I recently created a small Angular web application and decided to create a Header component using the command line ng g c Header. I then proceeded to write a brief paragraph in the header.component.html file. <p>header works!</p> An example o ...

Having trouble retrieving a value from a reference object in React Typescript?

Struggling with a login form issue in my React TypeScript project. Below is the code for the react login form: login-form.tsx import * as React from 'react'; import { Button, FormGroup, Input, Label } from 'reactstrap' ...

What could be causing the TypeScript type error within this Effector effect subscriber?

Working on a front-end application utilizing React, Typescript, Effector, FetchAPI, and other technologies. Created an Effector effect to delete an item in the backend: export const deleteItemFX = createEffect({ handler: (id: string) => { return ...

Setting default values for class members in Typescript is important for ensuring consistent behavior and

My model is pretty straightforward: export class Profile extends ServerData { name: string; email: string; age: number; } Whenever I make a server call using Angular 4's $http, I consistently receive this response: { name: string; email: ...

Switching between different types of generic functions in typescript

Is there a way to convert between these two types of generic functions: type Foo=<S>(a: S) => S type FooReturnType = ReturnType<Foo> // unknown type Bar<S> = { (a: S): S } type BarReturnType = ReturnType<Bar<string> ...

Transform Loopback 4 filter into a SQL WHERE condition

When using Loopback 4, the filter object that is received by functions like Get and Count appears as shown below: { where: { property: { op: value; } } } I am interested in converting this structure into an SQL WHERE clause to use it in ...

What is the purpose of `{ _?:never }` in programming?

I've been going through some TypeScript code and I stumbled upon a question. In the following snippet: type LiteralUnion<T extends U, U extends Primitive> = | T | (U & { _?: never }); Can anyone explain what LiteralUnion does and clarif ...

Error Encountered When Searching for Modules in a Yeoman-Generated Express TypeScript Project

After generating an express typescript project using yeoman, I encountered some errors whenever I tried running the application. The errors stated that it could not find modules such as "morgan", "body-parser", and "cookie-parser". Even though these module ...

Error encountered during Typescript compilation: The attribute 'raw' is not found within the context of the entity 'e' in express

In many instances, I have noticed that people use express.raw() or express.raw({type: 'application/json'}) as middleware in their requests... but is .raw() a legitimate method in Express? I am currently working with TypeScript and using Express ...

Does the React memo function modify the component's prop type?

I've come across a strange issue where defining two components causes compilation errors when written separately but not when written in the same file. test3.tsx import React from "react"; type ValueType = number[] | string[] | number | st ...

Is it recommended for TypeScript to automatically resolve the index.ts file as the default module file?

Struggling with getting the module resolution to work in TypeScript. Consider the following file structure: /modulename/index.ts Should it be resolved like this? import * as modulename from "modulename" I can't seem to make it work. However, imp ...

What is the process for exporting libraries in TypeScript?

Encountering an error when attempting to export socket.io using this method import socketIOClient from 'socket.io-client';. The error message is TS1192: Module '"***/node_modules/socket.io-client/build/index"' has no default e ...

Inference in Typescript - Detecting unknown key in an object

I am struggling to implement type inference from a props object that is passed to a component and then used in a render function. While I can retrieve the keys of the object correctly, all types are being interpreted as unknown. I need some assistance in f ...

Syncing data between local storage and a remote server using Ionic5 provider

I've been considering implementing a data provider that could store a duplicate of the backend data locally for quick access. I believe this concept is referred to as mirroring or something similar. Nevertheless, it must be synchronized and updated r ...

What are the properties used in functional components of React?

Seeking guidance on passing React component props to another component: interface IMyComponent { props: Props<any> } const MyComponent: FC = ({ props }) => { } Previously, I attempted to utilize the React.Props type after consulting this que ...