Issue a tslint warning when mockResolvedValueOnce is used with async/await

While working with the request-promise module, everything seems to be functioning correctly except for a warning from tslint.

Below is my unit test:

import * as request from 'request-promise';

jest.mock('request-promise', () => {
  return {
    __esModule: true,
    get: jest.fn(),
  };
});

describe('csv.service.ts', () => {
  it('should accurately mock the request-promise module', () => {
    expect(jest.isMockFunction(request.get)).toBeTruthy();
  });
  it('should accurately mock the get method', async () => {
    (request.get as jest.Mock).mockResolvedValueOnce('go?');
    const actualValue = await request.get('1');
    expect(actualValue).toBe('go?');
  });
});

The linter warns about using 'await' on a non-promise. (no-invalid-await)tslint(1)

It appears that request.get('1') is not being recognized as a promise after executing mockResolvedValueOnce on request.get.

update

If I remove the async/await, the second unit test will fail.

 FAIL  src/tests/services/core/csv.service.spec.ts
  csv.service.ts
    ✓ should accurately mock the request-promise module (5ms)
    ✕ should accurately mock the get method (9ms)

  ● csv.service.ts › should accurately mock the get method

    expect(received).toBe(expected) // Object.is equality

    Expected: "go?"
    Received: {}

    Difference:

      Comparing two different types of values. Expected string but received object.

      17 | 
      18 |     const actualValue = request.get('1');
    > 19 |     expect(actualValue).toBe('go?');
         |                         ^
      20 |   });
      21 | });
      22 | 

      at Object.it (src/tests/services/core/csv.service.spec.ts:19:25)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        1.203s, estimated 2s

Answer №1

To resolve this problem, I utilized typecast. By utilizing mockResolvedValueOnce, I am confident that request.get('1') becomes a Promise.

const finalizedResult = await (request.get('1') as PromiseLike<string>);

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

Encountered a runtime error in NgRx 7.4.0: "Uncaught TypeError: ctor is not a

I'm facing difficulties trying to figure out why I can't register my effects with NgRx version 7.4.0. Despite simplifying my effects class in search of a solution, I keep encountering the following error: main.79a79285b0ad5f8b4e8a.js:33529 Uncau ...

How do you define prop types when passing them in Nextjs?

Welcome to my page import { InferGetServerSidePropsType, GetServerSideProps } from 'next' import ProductList from '../../component/product/ProductList' export interface Item { title: string price: number } const products ...

Modify the key within an array of objects that share a common key

I have an object structured as follows: NewObjName: Object { OLDCOLUMNNAME1: "NEWCOLUMN_NAME1", OLDCOLUMNNAME2: "NEWCOLUMN_NAME2", OLDCOLUMNNAME3: "NEWCOLUMN_NAME3"} Next, there is an array containing objects in this format: ...

Animating progress bars using React Native

I've been working on implementing a progress bar for my react-native project that can be used in multiple instances. Here's the code I currently have: The progress bar tsx: import React, { useEffect } from 'react' import { Animated, St ...

Incorporating TypeScript into a project that already contains .js files

I currently have a NodeJS project with .js files written in ES6. I am interested in integrating typescript into this existing project. What steps should I follow? Can I simply introduce .ts files within the same directory structure? One issue I have encou ...

Converting a string[] to an EventEmitter string[] in Angular 4 with TypeScript: Step-by-step guide

Programming Language: Typescript – written as .ts files Development Framework: Angular 4 I'm currently working on an application that is supposed to add chips (similar to tags in Angular 1) whenever a user types something into the input box and hi ...

Having trouble utilizing a JavaScript file within TypeScript

I am currently exploring the integration of Three.js into an Angular application. Following the documentation, I imported Three.js using the following line: import * as THREE from 'three'; In addition, I installed the types for Three.js with th ...

Route Handler 13 is encountering difficulties in retrieving data from the body in the (app/api/auth) endpoint

Whenever I attempt to retrieve the body from the new export async function POST( req: Request), it seems to come through as a stream instead of the expected content type. The route handler can be found in api/auth/signup See folder layout image export asyn ...

When attempting to import css-animator in Angular2/Typescript, a 404 error is displayed, indicating that the

Recently, I delved into the world of Angular2 and decided to experiment with some animations using css-animator package.json "dependencies": { "@angular/common": "2.0.0-rc.3", "@angular/compiler": "2.0.0-rc.3", "@angular/core": "2.0.0-rc.3", ...

Passing both the object and its attributes simultaneously for reflect-metadata in TypeScript is a feature that closely resembles functionality found

Instead of using DataAnnotation in C# to add meta attributes on properties, I am seeking a similar functionality in TypeScript for a ldap model class. The goal is to have decorators that can set the LDAP attribute used in the LDAP directory internally. ex ...

Leverage the power of InfiniteSWR in your project by integrating it seamlessly with

If you're looking for a comprehensive example of how to integrate useSWR hooks with axios and typescript, check out the official repository here. import useSWR, { SWRConfiguration, SWRResponse } from 'swr' import axios, { AxiosRequestConfig, ...

Node OOM Error in Webpack Dev Server due to Material UI Typescript Integration

Currently in the process of upgrading from material-ui v0.19.1 to v1.0.0-beta.20. Initially, everything seems fine as Webpack dev server compiles successfully upon boot. However, upon making the first change, Node throws an Out of Memory error with the fol ...

What is the significance of var-less variables in TypeScript class definitions?

Why is it that when creating a component class in Angular2, we don't need to use var when declaring a new variable? For example: @Component({ selector: 'my-app', template: ` <h1>{{title}}</h1> ` }) export class AppCo ...

Encountering a Problem with HTTP Requests in Angular 2

Seeking assistance with a technical issue. My objective: Make a REST API call to retrieve JSON data and resolve an Angular 2 promise. ServerAPI built with Node.js/ExpressJS/Lodash Sample of server.js file: var express = require('express'); va ...

Uh-oh! Angular 6 has encountered an unexpected error with template parsing

I am currently working on an Angular application where I have integrated the FormsModule from '@angular/forms' in my app.module.ts. However, despite this, I keep encountering the error message No provider for ControlContainer. Error log: Uncaug ...

Is there a way to apply the same technique to a dynamic select option in Angular?

My array is dynamic and has an onChange method in the select option. The issue arises when I add a new array and select the new option, as it causes the first array to reset. Here's a snippet of my array structure: <ng-container formGroupName=&qu ...

The "shape" property is not available while utilizing generics with toZod

Short version: I encountered a type error, and here is the link to the TS PLAYGROUND I am looking to ensure type safety when creating zod schemas. To achieve this, I define the data type like so: type Option = { id: number }; Using this type definition ...

Encountered an issue with valid types while executing the following build

Encountering an error when attempting to run the next build process. https://i.stack.imgur.com/qM3Nm.png Tried various solutions including updating to ES6, switching the module to commonJs, downgrading webpack to version 4 with no success. The only worka ...

What is the process of bringing in a Svelte component into a Typescript file?

Can a Svelte component be imported into a Typescript file and successfully compiled by Rollup? While the following code works fine as a Javascript file, it encounters errors when converted to Typescript, as the TS compiler struggles with a .svelte file: i ...

Having trouble accessing store state in Angular with NGXS

In the parent component, I am dispatching an action and hoping to receive the dispatched array in the child component. To achieve this, I have implemented the following code: export class ListComponent implements OnInit { @Select(ProductState.getProductD ...