Encountering a Jest error stating "Function is not defined" while attempting to instantiate a spy in TypeScript

I'm attempting to simulate Cloudwatch in AWS using Jest and typescript, but I'm encountering an issue when trying to create a spy for the Cloudwatch.getMetricStatistics() function.

The relevant parts of the app code are as follows:

import AWS, { CloudWatch } from 'aws-sdk';
const cloudWatch = new AWS.CloudWatch();
/* build params */
const metrics = cloudWatch.getMetricStatistics(params).promise();

The test code is outlined below with comments.

const mockGetMetricStatisticsOutput = {
  Datapoints: {
    reduce: jest.fn().mockImplementation(() => 1),
  },
} as unknown as PromiseResult<AWS.CloudWatch.GetMetricStatisticsOutput, AWS.AWSError>;

const getMetricStatisticsSpy = jest.fn().mockReturnValue({
  promise: () => new Promise((resolve) => resolve(mockGetMetricStatisticsOutput)),
}); 

jest.mock('aws-sdk', () => ({
  CloudWatch: jest.fn(() => ({

    /* THIS WORKS, but I cannot spy on the getMetricsStatistics function so TEST 1 fails */
    getMetricStatistics: jest.fn().mockReturnValue({
      promise: () => new Promise((resolve) => resolve(mockGetMetricStatisticsOutput)),
    }),

    /* The following two definitions result in the error shown - even though the spy is defined exactly like that above  */

    // getMetricStatistics: () => getMetricStatisticsSpy, /* ERROR, Promise not a function */

    // getMetricStatistics: () => Promise.resolve(getMetricStatisticsSpy), /* ERROR, Promise not a function */
  })),
}));

The issue arises when trying to utilize the getMetricsSpy, which is defined identically to the functioning inline definition within the code. When attempting to use the spy as displayed in the commented out lines, I receive an error in the app code on the mentioned line:

const metrics = cloudWatch.getMetricStatistics(params).promise();

The error states that "promise is not a function." This occurs while running the test.

Any insights into what I might be doing incorrectly here?

Answer №1

This just seems off:

CloudWatch: jest.fn(() => ({

As per the documentation, I believe you should use:

CloudWatch: () => ({

jest.fn() is used for tracking function calls for testing purposes. However, in this case, a generic function is expected, which might be causing conflicts with jest.

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

Intercepting HTTP requests in Angular, but not making any changes to the

Working on Angular 13, I am trying to attach a JWT token to the headers in order to access a restricted route on the backend. However, after inspecting the backend, it seems that the JwtInterceptor is not modifying the HTTP request headers. I have included ...

How can you store form field validation rules (for example, firstname.dirty) in an array within TypeScript in Angular?

How do I save form field validation rules in an array? What should replace /'''''HERE'''''/ with? formfields: Array<Object> = [ {label: "Employer:", control: "employer", val ...

Is there a way for me to retrieve the value that has been set within the cy.get() function in Cypress using Typescript?

Is there a way to retrieve the value of the getLength function without it returning undefined? How can I access the value in this case? Here is my code snippet: const verifyValue = () => { const selector = 'nz-option-container nz-option-item&apo ...

Angular 2 Custom Pipe Magic

I'm brand new to using the Angular 2 framework and I'm attempting to create a custom filter. app.component.ts import {Component} from 'angular2/core'; import {HTTP_PROVIDERS} from 'angular2/http'; @Component({ selector: ...

receiving a null value in the JSON response

Preparing for the client to register. This function is responsible for registering a client. registerAsClient(){ this.loading =this.loadingCtrl.create({ content:"Setting up Account" }); this.loading.present(); this.buildClientData(); console.log( ...

How to Retrieve Input Field Value Using Cypress Custom Command

Is there a way to retrieve the value of an input[text] element within a custom command? Cypress.Commands.add('extendValue', { prevSubject: 'element' }, (subject: JQuery<HTMLElement>, extension: string): any => { const r ...

determine function output based on input type

Here's a question that is somewhat similar to TypeScript function return type based on input parameter, but with a twist involving promises. The scenario is as follows: if the input is a string, then the method returns a PlaylistEntity, otherwise it ...

Do constructors in TypeScript automatically replace the value of `this` with the object returned when using `super(...)`?

I’m having some trouble grasping a concept from the documentation: According to ES2015, constructors that return an object will automatically replace the value of “this” for any instances where “super(…)” is called. The constructor code must ...

Highcharts - Customize Pie Chart Colors for Every Slice

I'm working on an angular app that includes highcharts. Specifically, I am dealing with a pie chart where each slice needs to be colored based on a predefined list of colors. The challenge is that the pie chart is limited to 10 slices, and I need to a ...

Using TypeScript to Load JSON Data from a Folder

I'm a newcomer to TypeScript and encountering an issue. My task involves dynamically loading objects from a directory that houses multiple JSON files. The file names are generated through an export bash script populating the resource directory. I wan ...

Steps to enable the submit button in angular

Here's the code snippet: SampleComponent.html <nz-radio-group formControlName="radiostatus" [(ngModel)]="radioValue" (ngModelChange)="onChangeStatus($event)"> <label nz-radio nzValue="passed">Passed</label> <label nz-rad ...

The method of evaluating in-line is distinct from evaluating outside of the

What causes the compiler to produce different results for these two mapped types? type NonNullableObj1<O> = {[Key in keyof O] : O[Key] extends null ? never : O[Key]} type NotNull<T> = T extends null ? never : T; type NonNullableObj2<T> = ...

Ways to modify this request in order to update the current status

How can I optimize these calls to avoid repeating the same sentence for refreshing the state? I'm not looking for a major overhaul, just some suggestions like putting this call inside a function and invoking it when needed... export const CategoriesPa ...

Steps for generating an instance of a concrete class using a static method within an abstract class

Trying to instantiate a concrete class from a static method of an abstract class is resulting in the following error: Uncaught TypeError: Object prototype may only be an Object or null: undefined This error occurs on this line in ConcreteClass.js: re ...

Angular TypeScript test checking file size with Jasmine

Seeking optimal method for testing File size during input type="file" change event. Currently, my test specification appears as follows: it('attach file with too large size', () => { const file: File = { name: 'filename', ...

Mocking a React component with Jest's MockImplementation

Currently, I am in the process of testing a react component that renders another component. This secondary component makes an API call to fetch data which is then displayed on the screen. My goal is to understand how I can mock this particular component&ap ...

Using Vuelidate with Vue 3, vue-class-component, and TypeScript combination

Is there anyone who has successfully implemented Vuelidate with Vue 3 using the Composition API? Although Vuelidate is still in alpha for Vue 3, I believe that if it works with the Composition API, there must be a way to make it work with classes as well. ...

What are the benefits of using material-ui@next without the need for

Thinking about creating a project using material-ui@next, but trying to avoid using withStyles. However, encountering issues with the draft of TypeScript that includes the decorator @withStyles. This leads to one question - is it possible to use material ...

Utilizing external clicks with Lit-Elements in your project

Currently, I am working on developing a custom dropdown web component using LitElements. In the process of implementing a feature that closes the dropdown when clicking outside of it, I have encountered some unexpected behavior that is hindering my progres ...

Unlocking the Secrets of AnimatedInterpolation Values

I have a question about how to access the value of an AnimatedInterpolation in react-native without resorting to calling private code. To achieve this, I first create an animated value and then wrap it in an interpolation like so: animated = new Anima ...